c++This指针及其应用
时间: 2023-09-11 17:07:28 浏览: 135
在 C++ 中,this 指针是一个隐含于每个非静态成员函数中的指针,它指向调用该函数的对象。
下面是一个示例:
```cpp
#include <iostream>
class MyClass {
public:
void printAddress() {
std::cout << "Address of this pointer: " << this << std::endl;
}
};
int main() {
MyClass obj1, obj2;
obj1.printAddress();
obj2.printAddress();
return 0;
}
```
输出:
```
Address of this pointer: 0x7fff5fbff6b7
Address of this pointer: 0x7fff5fbff6b6
```
在上面的示例中,我们定义了一个名为 MyClass 的类,并在其中定义了一个名为 printAddress 的成员函数,该函数输出 this 指针的地址。在 main 函数中,我们创建了两个 MyClass 对象 obj1 和 obj2,并对它们都调用了 printAddress 函数。输出结果显示,这两个对象的 this 指针指向的地址是不同的,这是因为它们是不同的对象。
this 指针的应用非常广泛,其中一个常见的用法是在成员函数中返回对象本身的引用,即 `return *this;`。这在编写链式调用的代码时非常方便,例如:
```cpp
class MyClass {
public:
MyClass& setValue(int value) {
this->value = value;
return *this;
}
MyClass& setName(const std::string& name) {
this->name = name;
return *this;
}
private:
int value;
std::string name;
};
int main() {
MyClass obj;
obj.setValue(10).setName("example");
return 0;
}
```
在上面的示例中,我们定义了两个成员函数 setValue 和 setName,它们都返回对象本身的引用,这样我们就可以使用链式调用来设置对象的值。在 main 函数中,我们创建了一个 MyClass 对象 obj,并对它使用了两个成员函数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)