虚函数不解析大多数派生类方法

Com*_*erd 1 c++ debugging polymorphism object

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

 }
Run Code Online (Sandbox Code Playgroud)

shape [0]已初始化为Square.当我调用shape-> get_x时,我无法理解为什么shape-> get_x没有解析为最派生类而是解析为shape-> get_x的基类方法.我已经在我的基类中创建了get_x方法virtual.

有人可以向我解释为什么以及如何解决这个问题?

Dan*_*rey 7

在这些方面:

ShapeTwoD shape[100];
shape[0] = *s;
Run Code Online (Sandbox Code Playgroud)

你有"切片".你的shape数组包含ShapeTwoDs,你从*s第一个分配ShapeTwoD.这不会改变类型shape[0],因此它不是类型的对象Square.多态性只能在使用指针时起作用:

ShapeTwoD* shape[100]; // now you have 100 (uninitialized) pointers
shape[0] = s;

cout << shape[0]->get_x(0);
Run Code Online (Sandbox Code Playgroud)