Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

this指针在c++中作用

作者:你不爱我就滚。   发布日期:2026-02-25   浏览:98

#include <iostream>
using namespace std;

class Example {
public:
    void printAddress() {
        // this指针指向调用该成员函数的对象
        cout << "The address of the object is: " << this << endl;
    }

    void setValue(int val) {
        // 使用this指针区分成员变量和参数名称相同的情况
        value = val;  // 等价于 this->value = val;
    }

    int getValue() const {
        return value;
    }

private:
    int value;
};

int main() {
    Example obj;

    // 调用printAddress,输出对象的地址
    obj.printAddress();

    // 设置value的值
    obj.setValue(10);

    // 获取并打印value的值
    cout << "The value is: " << obj.getValue() << endl;

    return 0;
}

解释说明:

  1. this指针的作用:在C++中,this是一个隐式指针,它指向调用成员函数的对象。每个非静态成员函数都有一个隐含的this指针。
  2. 示例代码解释
    • Example类中的printAddress函数使用this指针来输出当前对象的地址。
    • setValue函数展示了如何使用this指针来区分成员变量和同名的参数。
    • getValue函数返回成员变量value的值。
  3. 主函数
    • 创建了一个Example类的对象obj
    • 调用了printAddress函数来输出对象的地址。
    • 调用了setValue函数来设置成员变量value的值。
    • 最后,调用了getValue函数来获取并打印value的值。

通过这个例子,可以看到this指针在C++中的作用和用法。

上一篇:c++如何四舍五入取整数

下一篇:stl c++

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++框架代码

c++格式化字符串

c++ orm框架

c++ find_if

c++ random函数用法

队列c++

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站