【问题标题】:Call parent constructor with private members in parent class在父类中调用具有私有成员的父构造函数
【发布时间】:2015-02-22 23:32:47
【问题描述】:

可以私下调用拥有其成员的父构造函数吗? 我知道受保护的可以,但我更喜欢使用私有,有什么办法可以解决这个问题吗?

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

【问题讨论】:

  • 我不明白这个问题。你有一个Product(std::string id, std::string description, double rateIVA);,它填充了产品的三个成员变量(至少我认为是这样),并且它是公开的。只是在子构造函数的初始化列表中调用它? (子构造器需要更多的params来获取父级的值,但是private没有问题)
  • 私有继承也可以,看这个问题:stackoverflow.com/questions/15042921/…
  • @deviantfan:你什么意思?该链接与私有构造函数无关。
  • @swang 啊抱歉,不知道我在那里读到了什么

标签: c++ oop


【解决方案1】:

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

class Parent {
    int mem_;

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

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

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

【讨论】:

  • 谢谢!正如您所说,它确实有效,即使它正在初始化的成员是私有的,父的构造函数也是公共的,因此您可以访问它。
  • 没问题。由于您是新用户,我可能应该提一下,您可以通过单击答案左侧数字下方的复选标记将答案标记为“已接受”,以便其他人可以从提供的答案中受益
猜你喜欢
  • 1970-01-01
  • 2020-11-08
  • 2014-12-16
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多