Exercise 13.5: Given the following sketch of a class, write a copy constructor that copies all the members. Your constructor should dynamically allocate a new string (§ 12.1.2, p. 458) and copy the object to which ps points, rather than copying ps itself.
如下面这样的类别定义,试着针对它写出一个拷贝建构器来拷贝它所有的资料成员。这个拷贝建构器应该要能动态配置出一个新的string(§12.1.2,页458)以拷贝ps指标指向的物件,而不是只是拷贝ps而已
class HasPtr {public:HasPtr(const std::string &s = std::string()):ps(new std::string(s)), i(0) { }private:std::string *ps;int i;};
#include<string>class HasPtr{public: HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0) {} HasPtr(const HasPtr& ) :ps(new std::string(*ps)),i(i){}//拷贝建构器private: std::string* ps; int i;};int main() { HasPtr hp; HasPtr hp2("守真"),hp1(std::string("阿弥陀佛")); hp = hp1; hp1 = hp2;}
https://play.google.com/books/reader?id=J1HMLyxqJfgC&pg=GBS.PT923
https://drive.google.com/open?id=1Zg0rM8B-4fOIyuqgAnFzJrJyuNaDrSPv
C++自修入门实境秀 529 重新译撰 《C++ Primer 5th》
13.1.2. The Copy-Assignment Operator
全部:http://bit.ly/2NoA2ID 原档下载:http://bit.ly/2Ixe2Vc
课文: http://bit.ly/2FIHV57
http://bit.ly/2mttmfa(第二篇)
第10-11章: http://bit.ly/2MuPmiZ
章12: http://bit.ly/2Rw53sH
重译12章:http://bit.ly/2V8UgZ7
http://bit.ly/2G2fPSg (docx)
重译11章:http://bit.ly/39P7HRU
第三篇:http://bit.ly/2UaFbDY
第三篇13章:http://bit.ly/33mh49y
讲义下载:
http://bit.ly/2khF8Ic (全部)
程式码:
https://github.com/oscarsun72/prog1
缘起:http://bit.ly/2XwHOUH