#include<iostream.h>
class point
{
public:
int x;
int y;
point()
{
x=0;
y=0;
}
point(int a,int b)
{
x=a;
y=b;
}
void output()
{
cout<<x<<endl<<y<<endl;
}
void input(int x,int y)
{
x=x;
y=y;
}
};
void main()
{
point pt(5,5);
pt.input(10,10);
pt.output();
}
有人可能会认为在input(int x,int y)函数中,利用形参x和形参y对point类中的成员变量x和y进行了赋值,其实因为变量的可见性,point类的成员变量x和y在input(int x,int y)中是不可见的,所以实际上是将形参x的值赋给了形参x,形参y的值赋值给了形参y,没有给point类的成员变量x和y进行赋值,所以程序运行的结果是5,5.
想在input(int x,int y)函数中对point类的成员变量x和y进行赋值:
(1)将input函数的参数名改为input(int a,int b)。
(2)利用this指针,
#include<iostream.h>
class point
{
public:
int x;
int y;
point()
{
x=0;
y=0;
}
point(int a,int b)
{
x=a;
y=b;
}
void output()
{
cout<<x<<endl<<y<<endl;
}
void input(int x,int y)
{
this->x=x;
this->y=y;
}
};
void main()
{
point pt(5,5);
pt.input(10,10);
pt.output();
}
运行结果为10,10