#include <iostream>
using namespace std;
class ShapeTwoD
{
public:
virtual int get_x(int);
protected:
int x;
};
class Square:public ShapeTwoD
{
public:
void set_x(int,int);
int get_x(int);
private:
int x_coordinate[3];
int y_coordinate[3];
};
int main()
{
Square* s = new Square;
s->set_x(0,20);
cout<<s->get_x(0)
<<endl;
ShapeTwoD shape[100];
shape[0] = *s;
cout<<shape->get_x(0); //outputs 100 , it doesn't resolve to
// most derived function and output 20 also
}
void Square::set_x(int verticenum,int value)
{
x_coordinate[verticenum] = value;
}
int Square::get_x(int verticenum)
{
return this->x_coordinate[verticenum];
}
int ShapeTwoD::get_x(int verticenum)
{
return 100;
}
形状 [0] 已初始化为 方形 。当我打电话给形状>get_x时,我无法理解为什么 shape->get_x 不解析为派生最多的类,而是解析为基类形状>get_x类方法 .我已经在我的基类中使get_x方法虚拟。
有人可以向我解释为什么以及如何解决此问题吗?
在这些行中:
ShapeTwoD shape[100];
shape[0] = *s;
你有"切片"。您的shape
数组包含 ShapeTwoD
s,您可以从 *s
分配给第一个ShapeTwoD
。这不会改变shape[0]
的类型,所以它不是类型Square
的对象。多态性只有在使用指针时才能工作:
ShapeTwoD* shape[100]; // now you have 100 (uninitialized) pointers
shape[0] = s;
cout << shape[0]->get_x(0);