c++中的this的作用及使用方法

在c++中,this是一个指向当前对象的指针。它是一个隐含的指针,可以在类的成员函数中使用。

在类的成员函数内部使用this关键字时,它将指向调用该成员函数的对象的地址。通过this指针,可以访问对象的成员变量和成员函数。

使用this的示例代码如下,

class Point {
private:
    int x;
    int y;

public:
    Point(int x, int y) {
        this->x = x;
        this->y = y;
    }

    void setCoordinates(int x, int y) {
        this->x = x;
        this->y = y;
    }

    int getX() const {
        return this->x;
    }

    int getY() const {
        return this->y;
    }

    void printCoordinates() const {
        std::cout << "Coordinates: (" << this->x << ", " << this->y << ")" << std::endl;
    }
};

int main() {
    Point p1(2, 3);
    p1.printCoordinates(); // 输出:Coordinates: (2, 3)

    p1.setCoordinates(5, 7);
    p1.printCoordinates(); // 输出:Coordinates: (5, 7)

    std::cout << "X coordinate: " << p1.getX() << std::endl; // 输出:X coordinate: 5
    std::cout << "Y coordinate: " << p1.getY() << std::endl; // 输出:Y coordinate: 7

    return 0;
}

Point类表示一个二维坐标点,

随后构造函数使用this指针来区分成员变量x和y,

setCoordinates()函数使用this指针来设置对象的坐标,

getX()和getY()函数使用this指针返回对象的坐标,

printCoordinates()函数使用this指针打印对象的坐标。

通过使用this指针,我们可以在成员函数中访问对象的成员,避免命名冲突,并确保正确地引用当前对象。

  • 13
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

chen_znn

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

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

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

打赏作者

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

抵扣说明:

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

余额充值