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

 }

shape[0] は Square に初期化されています。shape->get_x を呼び出すと、 shape->get_x が最も派生したクラスに解決されず、 shape->get_x の基本クラス メソッドに解決される理由がわかりません。基本クラスで get_x メソッドを既に virtual にしています。

誰かがこの問題を解決する理由と方法を説明できますか??

4

1 に答える 1

7

これらの行で:

ShapeTwoD shape[100];
shape[0] = *s;

あなたは「スライス」を持っています。配列には sshapeが含まれており、 fromを最初のShapeTwoDに割り当てます。これは の型を変更しないので、型のオブジェクトではありません。ポリモーフィズムは、ポインターを使用する場合にのみ機能します。*sShapeTwoDshape[0]Square

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

cout << shape[0]->get_x(0);
于 2013-10-20T12:00:02.077 に答える