在父 class 中使用私有成员调用父构造函数

Call parent constructor with private members in parent class

是否可以私下调用具有其成员的父构造函数? 我知道使用 protected 这个是可行的,但我更喜欢使用 private,有什么办法可以解决这个问题吗?

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;
};

如果父类的构造函数是publicprotected,那么调用它是没有问题的,即使它初始化的成员是私有的。虽然不清楚你的例子将如何初始化父对象,所以我会写一些更简单的东西让事情更清楚:

class Parent {
    int mem_;

public:
    Parent(int mem) : mem_(mem) { }
};

class Child : public Parent {
public:
    Child(int mem) : Parent(mem) { }
};

上面的例子可以,没问题。要注意的是,如果您想使用 Child class 修改 mem_ 成员,您只能使用 publicprotected 访问器方法Parent class 提供。