gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:06:46 24 4
gpt4 key购买 nike

我有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com