仅继承父构造函数的一些参数

时间:2017-01-06 21:21:00

标签: c++ visual-studio oop inheritance

我有以下类,我只希望继承的类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 个答案:

答案 0 :(得分:2)

解决方案1:您可以为A创建另一个只接受这两个参数的构造函数:

A(char *name, char* category) {...} 
...
B(char *name, char* category, char *location) :A(name, category) {...}

解决方案2:您只能为A(与您制作的同一个)保留一个构造函数,但quantityprice默认值:< / p>

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) {...}
相关问题