0

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

#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();

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

如果有人愿意帮忙,我会很高兴!非常感激

4

3 回答 3

2

发生的事情Rectangle::type是完全无关的Polygon::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";
}
于 2012-11-25T19:56:30.880 回答
0

type您有两个在 的实例中命名的成员Rectangle。由于私有成员Polygon只能由该类的成员函数访问,因此在Rectangle. 它甚至不是正确的阴影,因为在 中Rectangletype成员Polygon将无法访问。所以Polygon::getType返回type定义的 inPolygon而不是不相关的 in 定义的Rectangle

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

  • 在每个构造函数中定义type为受保护成员Polygon并分配给它。
  • 掉落type;声明getType为虚拟并在每个类中覆盖它,返回一个常量字符串。
  • 将 RTTI 用于它的好处:找出对象的实际类。
  • 设计你的程序,这样你就不需要告诉对象的确切类型。这通常是最好的。每次你需要为不同的子类提供不同的行为时Polygon,编写一个实现特定行为的虚成员函数。
于 2012-11-25T20:01:16.500 回答
0

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

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

Rectangle::Rectangle()
    Polygon()
{
    type = "rectangle";
}
于 2012-11-25T20:03:52.377 回答