VC++ this指针(Point函数中的成员变量对于是 函数void input(int x, int y)是不可见的)
#include <iostream>
using namespace std;
class Point
{
public:
int x;
int y;
Point()
{
x = 0;
y = 0;
}
Point(int a,int b)
{
x = a;
y = b;
}
void input(int x, int y)
{
x = x;
y = y;
}
void output()
{
cout << x << endl << y << endl;
}
};
int main()
{
std::cout << "Hello World!\n";
Point Pt(5,5);
Pt.input(10, 10);
Pt.output();
return 0;
}
#include <iostream>
using namespace std;
class Point
{
public:
int x;
int y;
Point()
{
x = 0;
y = 0;
}
Point(int a,int b)
{
x = a;
y = b;
}
void input(int x, int y)
{
this->x = x;
this->y = y;
}
void output()
{
cout << x << endl << y << endl;
}
};
Point函数中的成员变量对于是 函数void input(int x, int y)是不可见的;当Point 对象Pt调用Pt.input(10,10),成员函数除了接收了两个实参外,还接收了Pt的对象地址,这个地址被一个隐藏的this指针所获取,它等价于this=&Pt。所有数据成员的访问都隐含地加上了前缀this->方可访问。