gpt4 book ai didi

c++ - 派生类中需要构造函数参数的成员对象如何初始化?

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:31 24 4
gpt4 key购买 nike

我想在我的 Base 类中包含一个 Composed 对象,并让不同的派生类对其进行不同的配置。但是 Composed 类需要构造函数中的参数,我无法控制它的架构。

编译器报告错误,因为 Composed 的参数应该在 Base 类的初始化时传递。但我只希望它在派生类中被初始化。这种情况怎么办?

class Base{
public:
Base(); //Error
protected:
Composed comp;
};
class Composed{
public:
Composed(int id):id(id);
private:
int id;
};
class Derived_1:public Base{
public:
Derived():comp(1234){};
};
class Derived_2:public Base{
public:
Derived():comp(2345){};
};

最佳答案

你必须将该参数传递给 Base,然后传递给 comp:

class Composed{
public:
Composed(int id):id(id);
private:
int id;
};
class Base{
public:
Base(int id):comp(id){}
protected:
Composed comp;
};
class Derived_1:public Base{
public:
Derived():Base(1234){};
};
class Derived_2:public Base{
public:
Derived():Base(2345){};
};

关于c++ - 派生类中需要构造函数参数的成员对象如何初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35649537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com