作者s3748679 (冷羽忆尘)
看板Programming
标题Re: [C++]有关string class的pointer要如何initialize
时间Mon Aug 1 15:43:00 2011
※ 引述《cgcheng (..)》之铭言:
: ※ 引述《[email protected] ()》之铭言:
: : 请教大家
: : 我在读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