C++ this指针的用法

this指针

C++中的对象(比如类实例)都具有一个特殊的指针变量——this指针,指向对象的内存地址,使用的时候,可以在类的成员函数中使用this指针来访问类的成员。

this指针访问类成员的语法

this->member

提示:类的友元函数或友元类不能通过this指针访问,因为它们并不是类的成员。

this指针实例代码

下面实例代码中,定义了一个类,并在类的构造函数中使用this指针访问类的其它的成员,用于赋值(初始化):

#include <iostream>
using namespace std;

class Fruit{
    public:
        string name;
        Fruit(string n){
            this->name = n;
        }
};

int main() {

    Fruit apple("苹果");
    cout << apple.name << endl;

    return 0;
    
}

代码编译运行后,得到输出:

苹果

免责声明:内容仅供参考,不保证正确性。


全栈后端 / C++教程 :
















Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.