C++(this指针)

发布时间 2023-12-15 10:29:26作者: 做梦当财神

在 C++ 中,this 是一个关键字,表示指向当前对象的指针。它是每个非静态成员函数的一个隐式参数,被用于指向调用该函数的对象。通过 this 指针,成员函数可以访问调用它的对象的成员变量和成员函数。

以下是一个简单的示例,演示了 this 指针的使用:

#include <iostream>

class MyClass {
public:
    void printAddress() {
        std::cout << "Address of the object: " << this << std::endl;
    }

    void printValues(int x, int y) {
        // 使用 this 指针访问成员变量
        std::cout << "Values in the object: " << this->x << ", " << this->y << std::endl;

        // 访问传递进来的参数
        std::cout << "Values passed as arguments: " << x << ", " << y << std::endl;
    }

private:
    int x = 0;
    int y = 0;
};

int main() {
    MyClass obj1, obj2;

    // 调用成员函数,传递 this 指针
    obj1.printAddress();
    obj2.printAddress();

    // 调用成员函数,使用 this 指针访问成员变量
    obj1.printValues(1, 2);

    return 0;
}
Address of the object: 0x7ffeefb3d2e8
Address of the object: 0x7ffeefb3d2f0
Values in the object: 0, 0
Values passed as arguments: 1, 2

在这个例子中:

  • this 指针用于在成员函数 printAddress() 中打印对象的地址。
  • 在成员函数 printValues() 中,使用 this 指针访问对象的成员变量 xy,并且也展示了如何访问传递给函数的参数 xy

需要注意的是,this 指针只能在非静态成员函数中使用,因为静态成员函数是与类本身相关,而不是与类的具体实例相关。在静态成员函数中,this 指针是无效的。

class MyClass {
public:
    static void staticFunction() {
        // 在静态成员函数中,this 指针无效
        // 以下代码会导致编译错误
        // std::cout << "Address in static function: " << this << std::endl;
    }
};