this指针

本文探讨了C++中this指针的作用,它如何在成员函数内部访问对象,同时指出了静态成员函数中this指针不可用的特性。通过实例和错误代码展示了两者之间的区别。
部署运行你感兴趣的模型镜像

this指针

this指针

在每一个成员函数中都包含一个常量指针,我们称其为 this 指针。this 是 C++ 的一个关键字,this 指针指向调用本函数的对象,其值为该对象的首地址。通过该指针,我们可以在成员函数的函数体内访问对象。

#include<iostream>
using namespace std;

class book
{
public:
    book(){price = 0.0; title = NULL;}
    void copy(book &b);

    void display();
private:
    double price;
    char * title;
};

void book::copy(book &b)
{
    //我们用 this 指针先判断被拷贝的对象的引用是否是调用该函数的对象自身,如果是的话则推出函数
    if(this == &b)
    {
        cout<<"same object!"<<endl;
        return;
    }
    else
    {
        price = b.price;
    }
}

void book::display()
{
    cout<<"display hello this"<<endl;
}

int main()
{
    book Alice;
    book Harry;
    Harry.copy(Alice);
    Harry.display();

    Harry.copy(Harry);
    Harry.display();

    return 0;
}

在这里插入图片描述

 static void setprice(double price)
    {
        this->price = price;//compile error
    }
//error In static member function 'static void book::setprice(double)':
// error: 'this' is unavailable for static member functions

this 指针出现在 static 成员函数中,编译出错。this 指针只能用于非静态成员函数内

reference

微学苑 C++ this

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

### 作用 `this` 指针C++ 中的一个关键概念,它在面向对象编程中扮演着重要的角色。`this` 指针是一个指向当前对象的指针,在成员函数中可以通过 `this` 指针来访问对象的成员变量和成员函数[^1]。 #### 解决名称冲突 当成员变量与函数参数同名时,可以使用 `this` 指针来区分它们。例如: ```cpp class Person { public: int age; Person(int age) { this->age = age; // 使用 this 指针明确指定成员变量 } }; ``` #### 访问对象自身 在成员函数内部,如果需要返回当前对象本身,可以使用 `*this` 来实现。例如: ```cpp class A { private: int x; public: A& setX(int x) { this->x = x; return *this; // 返回当前对象以支持链式调用 } }; ``` ### 使用方法 #### 获取对象地址 在成员函数中,可以通过 `this` 指针获取当前对象的地址。例如: ```cpp class A { public: void display() { std::cout << this << std::endl; // 输出当前对象的地址 } }; ``` #### 成员变量访问 通过 `this` 指针可以直接访问对象的成员变量。例如: ```cpp class A { private: int x; public: void display() { std::cout << this->x << std::endl; // 通过 this 指针访问成员变量 std::cout << (*this).x << std::endl; // 通过解引用 this 指针访问成员变量 } }; ``` #### 级联操作 利用 `*this` 可以实现级联操作,即连续调用成员函数。例如: ```cpp class A { private: int x; public: A& addX(int x) { this->x += x; return *this; // 支持链式调用 } void display() { std::cout << x << std::endl; } }; int main() { A a; a.setX(5).addX(10).display(); // 链式调用 } ``` ### 注意事项 - `this` 指针只有在成员函数中才有定义,创建一个对象后,不能通过对象直接使用 `this` 指针。 - 在类的非静态成员函数中返回类对象本身时,可以使用圆点运算符 `.` 或箭头运算符 `->`。 - `this` 指针的值不能被修改,但可以通过 `this` 指针修改其所指向的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静思心远

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值