class A
{
public:
A(const int n_);
A(const A& that_);
A& operator=(const A& that_);
};
A::A(const int n_)
{ cout << "A::A(int), n_=" << n_ << endl; }
A::A(const A& that_) // This is line 21
{ cout << "A::A(const A&)" << endl; }
A& A::operator=(const A& that_)
{ cout << "A::operator=(const A&)" << endl; }
int foo(const A& a_)
{ return 20; }
int main()
{
A a(foo(A(10))); // This is line 38
return 0;
}
执行此代码给出 o/p:
A::A(int), n_=10
A::A(int), n_=20
显然复制构造函数永远不会被调用。
class A
{
public:
A(const int n_);
A& operator=(const A& that_);
private:
A(const A& that_);
};
但是,如果我们将其设为私有,则会发生此编译错误:
Test.cpp:在函数'int main()'中:
Test.cpp:21:错误:'A :: A(const A&)'是私有
Test.cpp:38:错误:在此上下文中
为什么编译器在实际不使用复制构造函数时会抱怨?
我正在使用 gcc 版本 4.1.2 20070925 (Red Hat 4.1.2-33)