#include<iostream>
using namespace std;
class Test
{
/* Class data members */
public:
Test(Test &t) { /* Copy data members from t*/}
Test() { /* Initialize data members */ }
};
Test fun()
{
cout << "fun() Called\n";
Test t;
return t;
}
int main()
{
Test t1;
Test t2 = fun();
return 0;
}
上述C ++代码有什么问题?编译器抛出以下错误
error: no matching function for call to ‘Test::Test(Test)’
答案 0 :(得分:9)
您声明了一个复制构造函数,它需要非const
左值。但是,fun()
返回临时值,您无法将临时值绑定到非const
左值。您可能希望将复制构造函数声明为
Test(Test const& t) { ... }