0

ShapeTwoD と Square の 2 つのクラスがあります。Square は ShapeTwoD から派生しています。

class ShapeTwoD
 { 
   public:virtual int get_x()
          { return x;}

          void set_x(int x)
          {x = x; }

   private:
        int x;
 };


class Square:public ShapeTwoD
{    
    public:
          virtual int get_x()
          { return x+5; }

    private:
           int x;

};

私のメインプログラムでは

int main()
{
 Square* s = new Square;

s->set_x(2);

cout<<s->get_x()  //output : 1381978708 when i am expecting 2
    <<endl;




ShapeTwoD shape[100];

shape[0] = *s;

cout<<shape->get_x(); //output always changes when i am expecting 2


}

私が得ているコンソール出力は非常に奇妙です。

最初の出力は 1381978708 ですが、 2 であると予想しています。

2番目の出力は常に変化しますが、7になることも期待しています

仮想関数を使用して、最も派生したクラス メソッドに解決しようとしています。何が起こっているのか説明してもらえますか ???

4

3 に答える 3

1

コード内のコメントを見てください。

class ShapeTwoD
{ 
public:
    virtual int get_x()
    {
        return x; // outputs ShapeTwoD::x
    }

    void set_x(int x)
    {
        // x = x;   // sets x to x
        this->x = x // sets ShapeTwoD::x
    }

   private:
        int x;
 };


class Square:public ShapeTwoD
{    
public:
    virtual int get_x()
    {
        return x + 5; // Outputs Square::x
    }

private:
    int x;
};

int main()
{
    Square* s = new Square;

    s->set_x(2);

    cout<<s->get_x()  //output : 1381978708 when i am expecting 2
        <<endl;       // because Square::x is uninitialized

    ShapeTwoD shape[100];

    shape[0] = *s; // slices Square to ShapeTwoD

    cout<<shape->get_x(); //output always changes when i am expecting 2
                          // look at the comments to the set_x function
}

したがって、xは のように宣言されprivateているためShapeTwoDSquareアクセスできません。あなたがしなければなりません:

  1. で保護xするShapeTwoD
  2. xから削除Square
  3. に変更x = xします (またはメンバー変数の名前set_xを に変更します) 。this->x = x_x
于 2013-10-20T11:15:26.230 に答える
1

それは、各クラスに別々xのメンバーがいるからです。したがって、呼び出すと、オブジェクトs->set_x(2)の一部に設定されShapeTwoD、while はオブジェクトSquare::get_xの一部から取得されSquareます。

Squareクラスからメンバー変数を削除し、メンバー変数をShapeTwoD保護します。

于 2013-10-20T11:08:51.333 に答える
0

派生クラスの仮想メソッドでx基本クラスを隠す秒は必要ありません。x

class Square:public ShapeTwoD
{    
public:
      virtual int get_x()
      { return x+5; }
};

元のコードでは、setter fromが settingであるときにSquare::get_x()参照されます。Square::xShapeTwoDShapeTwoD::x

また、セッター自体が間違っています。

void set_x(int x)
{
    this->x = x;
}
于 2013-10-20T11:08:40.137 に答える