【发布时间】:2009-10-04 23:23:24
【问题描述】:
我有以下无法编译的代码。编译器错误是:
"error: no matching function to call B::B(B)",
candidates are B::B(B&) B::B(int)"
代码在以下两种情况下编译:
- 取消注释函数 B(const B&)
-
把'main'改成下面的
int main() { A a; B b0; B b1 = b0; return 0; }
如果我执行 1,代码会编译,但从输出中它说它正在调用“非 const 复制构造函数”。
谁能告诉我这里发生了什么?
using namespace std;
class B
{
public:
int k;
B()
{
cout<<"B()"<<endl;
}
B(int k)
{
cout<<"B(int)"<<endl;
this->k = k;
}
/*B(const B& rhs) {
cout<<"Copy constructor"<<endl;
k = rhs.k;
}*/
B(B& rhs)
{
cout<<"non const Copy constructor"<<endl;
k = rhs.k;
}
B operator=(B& rhs)
{
cout<<"assign operator"<<endl;
k = rhs.k;
return *this;
}
};
class A
{
public:
B get_a(void)
{
B* a = new B(10);
return *a;
}
};
int main()
{
A a;
B b0 = a.get_a(); // was a.just();
B b1 = b0 ;
return 0;
}
【问题讨论】:
-
对不起。它应该是 a.get_a()
标签: c++ constructor reference copy constants