[英]Call parent constructor with private members in parent class
It is possible to call the parent constructor having the members of it in private? 可以私有地调用其成员的父构造函数吗? I know that with protected this works, but I prefer to use private, is there any way to solve this?
我知道有保护这个作品,但我更喜欢使用私有,有什么方法可以解决这个问题?
class Product {
std::string id;
std::string description;
double rateIVA;
public:
Product(std::string id, std::string description, double rateIVA);
~Product();
// Abstract Methods / Pure Virtual Methods
virtual double getIVAValue() = 0;
virtual double getSaleValue() = 0;
// Virtual Method
virtual void print() const;
// Setters & Getters
void setId(std::string id);
std::string getId() const;
void setDescription(std::string description);
std::string getDescription() const;
void setRateIVA(double rateIVA);
double getRateIVA() const;
};
class FixedPriceProduct : protected Product {
double price;
public:
FixedPriceProduct();
FixedPriceProduct(double price); // Implement here
~FixedPriceProduct();
double getIVAValue();
double getSaleValue();
virtual void print() const;
};
If the parent's constructor is public
or protected
, then there is no problem with calling it, even if the members it is initializing are private. 如果父的构造函数是
public
或protected
,那么调用它是没有问题的,即使它正在初始化的成员是私有的。 Although it is not clear how your example will initialize the parent, so I'll just write something simpler to make things clearer: 虽然不清楚你的例子将如何初始化父,所以我只想写一些更简单的东西来使事情更清楚:
class Parent {
int mem_;
public:
Parent(int mem) : mem_(mem) { }
};
class Child : public Parent {
public:
Child(int mem) : Parent(mem) { }
};
The above example will work, no problem. 上面的例子可行,没问题。 The catch is that if you want to modify the
mem_
member using the Child
class, you can only do so using the public
and protected
accessor methods that the Parent
class provides. 问题是,如果要使用
Child
类修改mem_
成员,则只能使用Parent
类提供的public
和protected
访问器方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.