面试题答案
一键面试this指针的作用
在C++ 中,this
指针是一个隐含于每一个非静态成员函数中的特殊指针。它指向调用该成员函数的那个对象。通过 this
指针,成员函数可以访问调用它的对象的成员变量和其他成员函数。其主要作用如下:
- 区分同名变量:当成员函数的参数与成员变量同名时,可以使用
this
指针来明确地访问对象的成员变量,避免混淆。 - 返回对象自身的引用:在一些链式调用或者需要返回当前对象引用的场景下,
this
指针非常有用。
常见使用场景
场景一:在成员函数中访问成员变量
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int width, int height) {
// 使用this指针区分参数和成员变量
this->width = width;
this->height = height;
}
int getArea() {
return this->width * this->height;
}
};
在上述代码中,Rectangle
类的构造函数中,通过 this
指针明确指定是对对象的成员变量 width
和 height
进行赋值,而不是局部变量。
场景二:实现链式调用
class StringBuilder {
private:
std::string str;
public:
StringBuilder& append(const std::string& s) {
str.append(s);
return *this;
}
std::string toString() {
return str;
}
};
在 StringBuilder
类中,append
函数返回 *this
,这样可以实现链式调用,例如 StringBuilder sb; sb.append("Hello").append(" World");
。通过返回 *this
(即当前对象的引用),可以继续在返回的对象上调用其他成员函数。