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

use*_*567 -2 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;
}
Run Code Online (Sandbox Code Playgroud)

上面的C++代码有什么问题?编译器抛出以下错误.
error: no matching function for call to ‘Test::Test(Test)’

Die*_*ühl 9

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

Test(Test const& t) { ... }
Run Code Online (Sandbox Code Playgroud)