先看个例子:
class Point {//这个class用来表述“点”
public:
Point(int x, int y) : this->x(x), this->y(y) {
}
void setX(int x) {
this->x = x;
}
void setY(int y) {
this->y = y;
}
public:
int x;
int y;
};
在VS2013上,编译错误。提示语法错误“this”,应输入标识符。
原因:this指针属于对象,初始化列表在构造函数之前执行,在对象还没有构造完成前,使用this指针,编译器无法识别。
程序修改为如下,就可以正常工作。
class Point {//这个class用来表述“点”
public:
Point(int x, int y) : x(x), y(y) {
}
void setX(int x) {
this->x = x;
}
void setY(int y) {
this->y = y;
}
public:
int x;
int y;
};
在构造函数初始化列表中,不要使用this指针,直接给成员变量初始化。编译器可以区别出参数x和成员变量x。
有个概念很重要,构造函数中的内容,属于assignment,并不是初始化。
接下来,我们把代码修改下,在成员函数中不用this指针,而是直接用成员变量x或y,看看结果会是什么?
class Point {//这个class用来表述“点”
public:
Point(int x, int y) : x(x), y(y) {
}
void setX(int x) {
x = x;
}
void setY(int y) {
y = y;
}
public:
int x;
int y;
};
Point p(1, 2);
std::cout << "p.x: " << p.x << std::endl;
std::cout << "p.y: " << p.y << std::endl;
p.setX(3);
p.setY(4);
std::cout << "p.x: " << p.x << std::endl;
std::cout << "p.y: " << p.y << std::endl;
在VS2013上测试结果如下:
从执行结果来看,在p.setX(3)和p.setY(4)之后,p.x和p.y的值并不是3和4,而是初始值1和2。
原因:在成员函数setX(int x)和setY(int y)中,参数x和y变量标识符隐藏了成员变量x和y。