Re: [C++]有關string class的pointer要如何initialize
※ 引述《cgcheng (..)》之銘言:
: ※ 引述《how.bbs@bbs.csie.ntnu.edu.tw ()》之銘言:
: : 請教大家
: : 我在讀C++ Primer 第3版的411頁(英文版)時
: : 發現了一行指令是有關string class的pointer要initialize
: : 寫法是:
: : string *pstr_type2(pstr_type); //pstr_type為另一個string class的pointer
: : 令我不太了解的地方是pstr_type2本身為一pointer,我個人的看法是應該寫為
: : string *pstr_type2 = pstr_type
: : 才對,但是上述兩種寫法在Dev C++上執行,結果都正確
: : 第一種寫法似乎是呼叫string class的pointer的copy constructor去initialize
: : 但是string class的pointer可以這樣做嗎? why?
: 前面有推文,不過這篇來自外站,可能原波看不到推文
: 如果是 pointer,我覺得沒啥差
: string *pstr_type2(pstr_type) 跟 string *str_type2 = pstr_type 是一樣
: 的沒錯
: 不過我想書上寫的可能是 MyObj abc(def),可能類似這樣。跟 MyObj abc = def,
: 這兩者的確有點不同,比照上一段 pstr_type 的 case,前者是 pointer 的 case,
: 後者是屬於value 的 case
: 好比 strcmp(abc,def) 跟 if(abc == def) 這兩個並不相同,一個是 value compare
: 一個是 pointer compare,pointer 的操作通常是比較有效率一點
: c++ 更多的是用 reference,大部分的 case 用 reference 可能綽綽有餘,除了
: 使用別人的 api lib 之外,自己寫的 function 應該是用 reference 在 function
: 之間傳遞足夠矣
實際實驗一下以下三種方式
1. MyObj abc(def);
2. MyObj abc = def;
3. MyObj abc;
abc = def;
程式碼:
#include <iostream>
using namespace std;
class C1{
public:
C1() {cout << "default constructor" << endl;}
C1(const C1& c) {cout << "copy constructor" << endl;}
C1& operator=(const C1& c) {cout << "operator=" << endl; return *this;}
};
int main()
{
C1 t1;
C1 t2(t1);
C1 t3 = t1;
C1 t4;
t4 = t1;
system("pause");
return 0;
}
編譯環境:
Dev-C++ 4.9.9.2
輸出結果:
default constructor
copy constructor
copy constructor
default constructor
operator=
請按任意鍵繼續 . . .
結論:
可以看到
C1 t3 = t1;
並沒有喚起operator=,反而和
C1 t2(t1);
有一樣喚醒copy constructor。
接著看到
C1 t4;
t4 = t1;
則是分別喚醒default constructor和operator=。
大概就這樣吧^_^",有問題的話,請指教。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.164.82.202
討論串 (同標題文章)
Programming 近期熱門文章
PTT數位生活區 即時熱門文章
7
20