这个C ++代码有什么问题?编译错误:调用'Test :: Test(Test)'没有匹配函数

时间:2013-09-23 15:00:51

标签: c++ constructor

#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)’

1 个答案:

答案 0 :(得分:9)

您声明了一个复制构造函数,它需要非const左值。但是,fun()返回临时值,您无法将临时值绑定到非const左值。您可能希望将复制构造函数声明为

Test(Test const& t) { ... }