【发布时间】:2011-09-12 16:02:12
【问题描述】:
考虑以下几点:
class X {
public:
X(int i) { cout << "X(int i)" << endl; }
X(const X& x) { cout << "X(const X& x)" << endl; }
};
void main() {
X x1(1);
X x2 = X(1);
X x3 = (X)1;
}
运行此代码会产生以下输出:
X(int i)
X(int i)
X(int i)
我认为以上三个语句都是等效的,因为永远不会调用副本 CTOR。但是,将X 的副本 CTOR 更改为私有:
class X {
public:
X(int i) { cout << "X(int i)" << endl; }
private:
X(const X& x) { cout << "X(const X& x)" << endl; }
};
将无法编译(在 Visual Studio 2010 中)并出现此错误:
cannot access private member declared in class 'X'
所以看起来复制 CTOR 以某种方式涉及,虽然我不太明白如何。
谢谢
【问题讨论】:
标签: c++ copy-constructor access-modifiers