iT邦幫忙

1

C++ Primer 5th Edition Exercises(練習題)13.05

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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言