复制构造函数的const对象

时间:2012-02-28 12:53:01

标签: const copy-constructor

我正在阅读有关复制构造函数的内容。 任何机构都可以告诉我下面的陈述中发生了什么

class Base {
public:
Base() {cout << "Base constructor";}
Base(const Base& a) {cout << "copy constructor with const arg";}
Base(Base& a) {cout << "copy constructor with non-const arg"; return a;}
const Base& operator=(Base &a) {cout << "assignment operator with non-const arg"; return a;}
}

void main()
{
    Base a;
    Base b = Base(); // This is neither calling copy constructor nor assignment operator.
}

请告诉我“Base b = Base()”声明发生了什么。

1 个答案:

答案 0 :(得分:0)

将在三种情况下调用复制构造函数:

When an object is returned by value 
When an object is passed (to a function) by value as an argument 
When an object is thrown 
When an object is caught 
When an object is placed in a brace-enclosed initializer list 

将在下面调用赋值运算符:

B b;
b=a;

所以你的陈述:

Base b = Base(); 

不适合上述任何一项。