使用父类中的私有成员调用父构造函数

时间:2021-11-01 23:29:03

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

1 个解决方案

#1


0  

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. 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访问器方法。

#1


0  

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. 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访问器方法。