c++的this指针
时间: 2023-12-06 12:34:00 浏览: 91
C++中的this指针是一个指向当前对象的指针,它可以在类的成员函数中使用。this指针可以用来访问当前对象的成员变量和成员函数,也可以用来返回当前对象的引用。
在C++中,每个对象都有自己的一份成员变量,而成员函数则是所有对象共享的。当调用一个成员函数时,编译器会自动将当前对象的地址作为参数传递给该函数,这个参数就是this指针。
例如,下面是一个简单的示例:
```
class MyClass {
public:
void print() {
cout << "this is MyClass" << endl;
}
};
int main() {
MyClass obj;
obj.print(); // 相当于调用了 print(&obj);
return 0;
}
```
在上面的代码中,当调用 `obj.print()` 时,编译器会自动将 `&obj` 作为参数传递给 `print()` 函数,因此在 `print()` 函数中可以使用 `this` 指针来访问 `obj` 的成员变量和成员函数。
相关问题
c++ this指针
在给成员函数增加隐藏的指针参数时,编译器会将该指针指向调用函数的对象,也就是当前对象。这个指针就是this指针。在上述代码中,由于p是空指针,所以在调用p的成员函数Show()时,this指针被初始化为空指针。这使得函数体中对成员变量的操作无法进行,因此没有输出结果。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [[ C++ ] 一篇带你了解C++中隐藏的this指针](https://blog.csdn.net/qq_58325487/article/details/124785521)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
c++ this指针的意义
C++中的this指针是一个指向当前对象的指针,它可以在类的成员函数中使用。当一个对象调用它的成员函数时,编译器会将该对象的地址作为一个隐含参数传递给该函数,这个隐含参数就是this指针。通过this指针,我们可以访问当前对象的成员变量和成员函数。
例如,在以下代码中,this指针被用来访问对象的成员变量x:
```
class MyClass {
public:
void setX(int x) {
this->x = x;
}
private:
int x;
};
int main() {
MyClass obj;
obj.setX(10);
return 0;
}
```
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)