【发布时间】:2018-12-13 12:00:15
【问题描述】:
如果在c++ 中父子类有一个同名成员,我在c++ 编程中遇到了问题:
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(){x=1;}
void SetX(int i)
{
x=i;
}
};
class B:public A{
private:
int x;
public:
B(){}
int GetX()
{
return x;
}
};
int main() {
B b;
cout<<b.GetX()<<endl;
b.SetX(10);
cout<<b.GetX()<<endl;
return 0;
}
程序结果是:
-858993460
-858993460
为什么?返回的是哪个x?
感谢您的帮助。
【问题讨论】:
-
可以将其用于学习目的(请参阅当前答案),但这里真正的教训是“永远不要让自己陷入这种情况”:避免在基类和派生类中使用 2 个同名变量,这只会产生误导,而且很容易出错
-
我知道。这是我们老师给的程序。
标签: c++