C++(this指针)

在 C++ 中,this 指针是一个特殊的指针,它指向当前对象的实例。

在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。

this 是一个隐藏的指针,可以在类的成员函数中使用,它可以用来指向调用对象。

当一个对象的成员函数被调用时,编译器会隐式地传递该对象的地址作为 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;
    }
};


posted @ 2023-12-15 10:27  做梦当财神  阅读(59)  评论(0)    收藏  举报