【发布时间】:2013-10-20 11:03:30
【问题描述】:
我有 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
我正在尝试使用虚函数来解析到最派生的类方法, 有人可以向我解释发生了什么吗???
【问题讨论】:
-
行为看起来相当简单;你有两个
x成员变量;set_x正在修改基类(实际上不是,x=x什么都不做!),get_x正在返回(未初始化的)派生类。
标签: c++ debugging polymorphism virtual-functions