![](/img/trans.png)
[英]What is the term for an inheriting class constructor with different parameters?
[英]Inheriting only some of the parameters of the parent's constructor
我有以下类,我只希望继承的类 B 只有父类 A 的一些参数
class A{
private:
int quantity;
int price;
protected:
char *name;
char *category;
public:
A(int quantity, int price, char *name, char* category)
{ } // CONSTRUCTOR
};
class B: public A
{
private:
char *location;
public:
B(int quantity, int price, char *name, char* category, char *location) :A(quantity, price,name, category)
};
我想要做的是让 B 类只继承 A 的名称和类别,如下所示:
B(char *name, char* category, char *location) :A(name, category)
但这不起作用,我认为将这些属性设为私有会解决我的问题,但事实并非如此。 有没有办法做到这一点,或者我必须创建另一个具有所需属性的类?
解决方案 1:您可以为 A 创建另一个仅采用这两个参数的构造函数:
A(char *name, char* category) {...}
...
B(char *name, char* category, char *location) :A(name, category) {...}
解决方案 2:您只能为A
保留一个构造函数(与您创建的相同),但使用quantity
和price
默认值:
A(char *name, char* category, int quantity = 0, int price = 0) {...}
// Notice that the parameters that have default values must come at
// the end of the param list
...
B(char *name, char* category, char *location) :A(name, category) {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.