首页 > 解决方案 > 抽象类访问其子类函数

问题描述

是否可以从作为父级的抽象类的指针访问子级的函数成员?这是抽象类

class Item {
    public:
        virtual double getTotalPrice() = 0;
};

这是子班

class Product : public Item {
    protected:
        string name;
    public:
        Product() {}
        string getName() {}
        double getTotalPrice() {}
};

是否可以在主驱动程序中从 Item 类的实例访问此 getName() 函数,因为我还想显示总价和产品名称?

标签: c++inheritanceabstract-class

解决方案


  • virtual如果您应该能够delete通过基类指针访问对象,则需要您的基类具有析构函数。
  • 也做getName virtual
class Item {
public:
    virtual ~Item() = default;
    virtual const string& getName() /* const */ = 0;
    virtual double getTotalPrice() /* const */ = 0;
};

请注意,Product不允许您更改的课程存在轻微缺陷。

  • 它不会在应有的地方返回值。
  • getter 成员函数不是const.

如果您不能自己做,建议进行一些更改:

class Product : public Item {
private: // prefer private member variables
    string name;
public:
    Product() = default;
    const string& getName() const override { return name; }
    double getTotalPrice() const override {
       // why is this implemented here when there's no price to return?
       return {};
    }
};

推荐阅读