我有 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
}
因此,因为 x
在 ShapeTwoD
中声明为 private
,所以 Square
无法访问它。你必须做:
- 使
x
在ShapeTwoD
中受到保护 - 从
Square
中删除x
- 将
set_x
中的x = x
更改为this->x = x
(或者将成员变量重命名为_x
)
关于c++ - 虚函数输出奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476621/