简体   繁体   English

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

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

i have 2 classes, one class which inherits it's parameters from an abstract class: 我有2个类,一个类从抽象类继承其参数:

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

and another which has two overloaded constructors, one uses normal parameters and another, gets the same parameters but from the first class' already existing object: 另一个有两个重载的构造函数,一个使用普通参数,另一个使用相同的参数,但是从第一类已经存在的对象中获取相同的参数:

header file: 头文件:

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

cpp file: cpp文件:

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

but when i try to compile i get an error at the marked place "C2512 'Other': no appropriate default constructor available" 但是当我尝试编译时,在标记的位置“ C2512'Other':没有合适的默认构造函数”时出现错误

What could be the problem? 可能是什么问题呢? i really need to to pass that object into the constructor 我真的需要将该对象传递给构造函数

Here: 这里:

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

you need to construct the child object: 您需要构造子对象:

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

You don't have Child::Child() . 您没有Child::Child() Since you don't list o in the initializer list in the error line, Child::Child() is getting called. 由于您没有在错误行的初始化列表中列出o ,因此将调用Child::Child() This empty constructor is automatically added when there is no other constructor. 没有其他构造函数时,将自动添加此空构造函数。 Given that you have Child::Child(string s, int i) , compiler will not auto create Child::Child() . 假设您有Child::Child(string s, int i) ,编译器将不会自动创建Child::Child()

This occurs because Other has a Child member, but you haven't given Child a default constructor (a constructor that takes no arguments). 发生这种情况是因为Other具有Child成员,但是您没有给Child提供默认的构造函数(不带参数的构造函数)。 Since Child doesn't have a default constructor, the compiler has no idea how to create an instance of Child , so you have to tell it. 由于Child没有默认的构造函数,因此编译器不知道如何创建Child的实例,因此您必须告诉它。

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

I'm just guessing here but I suspect the Other constructor taking a string and an integer is supposed to use those arguments to construct the Child object. 我只是在这里猜测,但我怀疑Other构造函数采用字符串,而整数应该使用这些参数来构造Child对象。

Then you should do something like this instead: 然后,您应该执行以下操作:

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

And of course remove the s and i member variables from the Other class. 当然,还要从Other类中删除si成员变量。

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

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