我有两个类,其中一个类有另一个类的对象作为数据成员,它的构造函数接受类对象来初始化数据成员对象。
class x{
public:
x(int a, int b)
{ cout << a << b;}
};
class y{
x temp;
y(x& o){ this-> temp = o;}
};
但是编译器在 y::y(x&) 中显示错误:没有匹配的函数来调用 x::x()
我正在使用代码块 16.01
您已经定义了构造函数:
x(int a, int b)
在x
。这意味着编译器将不再为您定义任何构造函数,这包括x()
构造函数。所以,你可以只建x
有x(int, int)
。在您的代码中:
x temp;
y(x& o) { // < No initializer list
您尝试使用默认构造函数x
,但x
没有默认构造函数!要么定义一个,要么使用x
您提供的构造函数在初始值设定项列表中构造。
例如:
y(x& o) : x(0, 0) {
但是您将创建您的对象,然后您将使用隐式定义的copy-assignment
运算符来分配它,这有点浪费时间。您实际上可以通过使用以下方法解决所有这些问题copy-constructor
:
class x{
...
x(const x ©) { // Define a copy constructor or just use
// the implicitly defined one.
然后在y
,只需在y
的初始化列表中使用它:
x temp;
y(x& o) : temp(o) {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句