我对基类和子类函数继承非常困惑。 我有这些课程:
#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)时呢?
如果有人愿意,我们会很高兴! 非常感谢
答案 0 :(得分: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";
}
答案 1 :(得分:0)
type
的实例中有两个名为Rectangle
的成员。由于Polygon
的私有成员只能访问该类的成员函数,因此在Rectangle
中使用相同名称声明成员时,它们就好像不存在一样。它甚至不是正确的阴影,因为在Rectangle
中,type
的{{1}}成员将无法访问。因此,Polygon
会返回Polygon::getType
中定义的type
,而不会返回Polygon
中定义的无关{。}}。
您有几种方法可以解决您的问题:
Rectangle
定义为type
中的受保护成员,并在每个构造函数中为其分配。Polygon
;将type
声明为虚拟并在每个类中覆盖它,返回一个常量字符串。getType
的不同子类的不同行为时,请编写实现特定行为的虚拟成员函数。答案 2 :(得分:0)
您只需要在一个地方使用类型字符串 - 您的基类。因为您希望它可以在派生类中访问而不是您的用户访问,所以要保护它。在每个构造函数中,将其设置为适当的值:
Polygon::Polygon():
type("polygon")
{}
Rectangle::Rectangle()
Polygon()
{
type = "rectangle";
}