繁体   English   中英

如何将一个对象作为另一个类构造函数的参数传递?

[英]How to pass an object as another class constructor's parameter?

我有2个类,一个类从抽象类继承其参数:

class Child : public Base {
public:
    Child(string s, int i, ) : Base(s, i){};
    ... // methods
};

另一个有两个重载的构造函数,一个使用普通参数,另一个使用相同的参数,但是从第一类已经存在的对象中获取相同的参数:

头文件:

class Other {
private:
    string s;
    int i; 
    Child o;
public:
    Other(string str, int num);
    Other(Child ob);
};

cpp文件:

Other :: Other(string str, int num) : s(str), i(num) {/* this is where the error happens*/};
Other :: Other(Child ob) : o(ob) {
};

但是当我尝试编译时,在标记的位置“ C2512'Other':没有合适的默认构造函数”时出现错误

可能是什么问题呢? 我真的需要将该对象传递给构造函数

这里:

Other :: Other(string str, int num) : s(str), i(num)

您需要构造子对象:

Other :: Other(string str, int num) : s(str), i(num), o(str, num ) {}

您没有Child::Child() 由于您没有在错误行的初始化列表中列出o ,因此将调用Child::Child() 没有其他构造函数时,将自动添加此空构造函数。 假设您有Child::Child(string s, int i) ,编译器将不会自动创建Child::Child()

发生这种情况是因为Other具有Child成员,但是您没有给Child提供默认的构造函数(不带参数的构造函数)。 由于Child没有默认的构造函数,因此编译器不知道如何创建Child的实例,因此您必须告诉它。

Other :: Other(string str, int num) : s(str), i(num), o(some_value_of_type_Child) {};

我只是在这里猜测,但我怀疑Other构造函数采用字符串,而整数应该使用这些参数来构造Child对象。

然后,您应该执行以下操作:

Other:: Other(string str, int num) : o(str, num) {}

当然,还要从Other类中删除si成员变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM