c++ - 虚函数输出奇怪的值

标签 c++ debugging polymorphism virtual-functions

我有 2 个类:ShapeTwoD 和 Square。 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 。

第二个输出总是在变化,尽管我也希望它是 7

我正在尝试使用虚函数来解析最派生的类方法, 有人可以向我解释发生了什么吗???

最佳答案

看一下代码中的注释:

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
}

因此,因为 xShapeTwoD 中声明为 private,所以 Square 无法访问它。你必须做:

  1. 使 xShapeTwoD 中受到保护
  2. Square 中删除 x
  3. set_x 中的 x = x 更改为 this->x = x (或者将成员变量重命名为 _x )

关于c++ - 虚函数输出奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476621/

相关文章:

c++ - 为什么与 Direct X 链接会大大增加我的程序大小?

c++ - 使用 GetModuleHandle 获取指向 IMAGE_DOS_HEADER 的指针?

node.js - 如何使用 Node js 创建条件调试 Visual Studio Code

java - 如何防止Eclipse在调试中遇到断点时自动打开调试面板

eclipse - 使用 eclipse 调试 Node 应用程序

ruby-on-rails - Rails 多态模型中记录的唯一性验证

c++ - 使用可变参数模板的 mixin 继承的可见性规则

C++:初始化指向 int 的指针

c++ - 强制实例化派生类型而不是基类型

java - 在这个多态性练习中,我如何计算由一系列节点表示的方程式?