基类和子类函数继承混淆(C ++)

时间:2012-11-25 19:52:11

标签: c++

我对基类和子类函数继承非常困惑。 我有这些课程:

#include <point.h>

class Polygon{
public:
    Polygon();
    virtual ~Polygon();
    void addPoint(Point *p);
    std::string getType();
    Point* getPoint(int index);
    int getNumOfPoints();
    int getColor();
    virtual int area()=0;

private:
  std::vector<Point*> _points;

  int color;
  std::string type = "Polygon";

};

class Rectangle : public Polygon{
public:
    Rectangle();
    virtual ~Rectangle();
    virtual int area();

private:
    std::vector<Point*> _points;

    int color;
    std::string type = "Rectangle";
};

现在,主要是我这样做:

Rectangle rect();
rect.getType();

这给了我“Polygon”,而我想要“矩形” 我很确定我对继承感到困惑。所以,根据我的理解,基类函数是继承的,但是为什么当我运行它与对象基类的成员有关但不是实际对象(Rectangle)时呢?

如果有人愿意,我们会很高兴! 非常感谢

3 个答案:

答案 0 :(得分:2)

Rectangle::typePolygon::type完全无关。它是一个单独的数据成员,恰好具有相同的名称。

实现所需效果的一种方法是使getType()虚拟并覆盖每个派生类:

class Polygon {
public:
    virtual std::string getType() = 0;
    ...
}

class Rectangle: public Polygon {
public:
    virtual std::string getType();
    ...
}

std::string Rectangle::getType() {
    return "Rectangle";
}

答案 1 :(得分:0)

type的实例中有两个名为Rectangle的成员。由于Polygon的私有成员只能访问该类的成员函数,因此在Rectangle中使用相同名称声明成员时,它们就好像不存在一样。它甚至不是正确的阴影,因为在Rectangle中,type的{​​{1}}成员将无法访问。因此,Polygon会返回Polygon::getType中定义的type,而不会返回Polygon中定义的无关{。}}。

您有几种方法可以解决您的问题:

  • Rectangle定义为type中的受保护成员,并在每个构造函数中为其分配。
  • 放弃Polygon;将type声明为虚拟并在每个类中覆盖它,返回一个常量字符串。
  • 使用RTTI来获取它的好处:找出对象的实际类。
  • 设计您的程序,这样您就不需要告诉对象的确切类型。这通常是最好的。每当您需要getType的不同子类的不同行为时,请编写实现特定行为的虚拟成员函数。

答案 2 :(得分:0)

您只需要在一个地方使用类型字符串 - 您的基类。因为您希望它可以在派生类中访问而不是您的用户访问,所以要保护它。在每个构造函数中,将其设置为适当的值:

Polygon::Polygon():
        type("polygon")
{}

Rectangle::Rectangle()
    Polygon()
{
    type = "rectangle";
}
相关问题