【发布时间】:2013-06-26 09:26:18
【问题描述】:
我写了一个简单的代码,我的问题是:为什么item_base只是调用constrcut函数?应该item_base调用“复制构造函数”吗?我观察到当我创建item_base2时,它调用了“复制构造函数”,但item_base没有调用“复制构造函数”,有什么区别?
class Item_base {
public:
Item_base();
Item_base(int);
Item_base(const Item_base &base);
void operator=(const Item_base &item);
virtual ~Item_base();
};
Item_base::Item_base()
{
cout << "construct function" << endl;
}
Item_base::Item_base(int a)
{
cout << "arg construct function" << endl;
}
Item_base::Item_base(const Item_base &base)
{
cout << "copy function" << endl;
}
void Item_base::operator=(const Item_base &item)
{
cout << "= operator" << endl;
}
Item_base::~Item_base()
{
}
int main()
{
//cout << "Hello world!" << endl;
Item_base item_base = Item_base(1);//construct function
Item_base item_base2 = item_base;//copy construct function
Item_base item_base3;
item_base3 = item_base2;// =operator function
return 0;
}
【问题讨论】:
-
其实这个副本比较好:stackoverflow.com/questions/2847787/…
-
我相信在第一种情况下,
Item_base(1)的构造函数被调用,然后编译器只是在这里优化了一个临时对象的复制。
标签: c++