通过引用另一个类的构造函数传递对象时出错

Nil*_*esh 0 c++ constructor class

我有两个类,其中一个类有另一个类的对象作为数据成员,它的构造函数接受类对象来初始化数据成员对象。

class x{

public:
    x(int a, int b)
     { cout << a << b;}
  };

class y{

 x temp;

 y(x& o){ this-> temp = o;}
 };
Run Code Online (Sandbox Code Playgroud)

但编译器在 y::y(x&) 中显示错误:没有匹配的函数来调用 x::x()

我正在使用代码块 16.01

Fan*_*Fox 5

您已经定义了构造函数:

x(int a, int b)
Run Code Online (Sandbox Code Playgroud)

x。这意味着编译器将不再为您定义任何构造函数,这包括x()构造函数。所以你只能x用 来构建x(int, int)。在您的代码中:

 x temp;
 y(x& o) { // < No initializer list
Run Code Online (Sandbox Code Playgroud)

您尝试默认构造函数x,但x没有默认构造函数!定义一个,或者x使用您提供的构造函数在初始值设定项列表中构造。

例如:

y(x& o) : x(0, 0) {
Run Code Online (Sandbox Code Playgroud)

但是您将创建对象,然后使用隐式定义的copy-assignment运算符来分配它,这有点浪费时间。您实际上可以使用以下方法解决所有这些问题copy-constructor

 class x{
    ...
    x(const x &copy) { // Define a copy constructor or just use 
                       // the implicitly defined one.
Run Code Online (Sandbox Code Playgroud)

然后在 中,只需在的初始化器列表y中使用它:y

 x temp;
 y(x& o) : temp(o) {}
Run Code Online (Sandbox Code Playgroud)