类成员函数参数和类成员变量的可见性

来源:互联网 发布:网络咨询医生好做不 编辑:程序博客网 时间:2024/06/08 11:12
原文出处:EdwardLewis

一、如下示例
#include "iostream"
using namespace std;
class point{
public:
int x;
int y;
point() {}
point(int a,int b){x=a;y=b;}
void output()
{
cout<<x<<endl<<y<<endl;
}
void input(int a,int y)
{
x=a;
y=y;
}
};
int main()
{
point pt(5,5);
pt.input(10,10);
pt.output();
return 1;
}
二、问题
输出结果为10,5。不是我们10,10,为什么呢?
因为相对局部变量隐藏了外层局部变量的缘故。在
void input(int a,int y)
{
x=a;
y=y;
}
函数中,类的成员变量y被形参y所屏蔽隐藏,所以实际上是自己给自己赋值。
三、解决方法两个:
1、void input(int a,int b)
{
x=a;
y=b;
}
2、用this指定
void input(int x,int y)
{
this.x=x;
this.y=y;
}
0 0
原创粉丝点击