[英]Inheriting only some of the parameters of the parent's constructor
I have the following classes, and i only want that the inherited class B to have only some of the parameters of parent class A我有以下类,我只希望继承的类 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)
};
What i want to do is that making class B inherit only name, and category from A, like this:我想要做的是让 B 类只继承 A 的名称和类别,如下所示:
B(char *name, char* category, char *location) :A(name, category)
but it doesn't work, i thought that making those attributes private will solve my problem, but it didn't.但这不起作用,我认为将这些属性设为私有会解决我的问题,但事实并非如此。 Is there a way to do this, or i have to make another class with the required attributes?有没有办法做到这一点,或者我必须创建另一个具有所需属性的类?
Solution 1: You can make another constructor for A that takes only those two parameters:解决方案 1:您可以为 A 创建另一个仅采用这两个参数的构造函数:
A(char *name, char* category) {...}
...
B(char *name, char* category, char *location) :A(name, category) {...}
Solution 2: You can keep only one constructor for A
(the same one you made) but with default values for quantity
and price
:解决方案 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.