this指针

梦里梦外; 2022-04-23 12:18 277阅读 0赞

文章目录

    • this指针是常量指针,不可修改
    • 成员函数后加const
    • 静态成员函数没有this指针
    • 返回对象本身用 *this

this指针传递的是当前对象的指针,这样每个对象操作自己的成员变量

  • this指针是常量指针,不可修改

    class Goods
    {
    public:

    1. Goods(int w):m_weight(w)
    2. {
    3. }
    4. int Get()
    5. {
    6. this++; //报错,必须是可修改的左值 ,证明传递的是: Goods* const this
    7. return m_weight;
    8. }

    private:

    1. int m_weight;

    };


成员函数后加const

  • 如果一个成员函数后面加const修饰,修饰的是this指针,表示不可以通过this指针修改其对象内容

    class Goods
    {
    public:

    1. Goods(int w):m_weight(w)
    2. {
    3. }
    4. int Get()const //不能通过this进行修改值, 传递的是: const Goods* const this
    5. {
    6. m_weight++; //报错,this->m_weight++;
    7. return m_weight;
    8. }

    private:

    1. int m_weight;

    };

  • 使用情况:注意27行的注释

    include “stdafx.h”

    include

    include

    using namespace std;

  1. class Student
  2. {
  3. friend Student operator+(const Student& s1, const Student& s2);
  4. public:
  5. Student(int id) :m_id(id) { }
  6. int GetID()const
  7. {
  8. return m_id;
  9. }
  10. private:
  11. int m_id;
  12. };
  13. Student operator+(const Student& s1,const Student& s2)
  14. {
  15. Student tmp(s1.GetID()+s2.GetID()); //如果Student::GetID后面不加const报错,因为将GetID(Student* const s),将const s1赋值給s报错
  16. return tmp;
  17. }
  18. int main(void)
  19. {
  20. Student A(1);
  21. Student B(2);
  22. Student C = A + B;
  23. cout << C.GetID() << endl;
  24. return 0;
  25. }

静态成员函数没有this指针

  • 静态成员函数只能访问静态成员变量,因为静态成员函数不属于对象,所以没有this指针

返回对象本身用 *this

  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;
  4. class Goods
  5. {
  6. public:
  7. Goods(int w):m_weight(w)
  8. {
  9. }
  10. Goods& Add(Goods& another) //返回是自身引用,还可以做左值
  11. {
  12. m_weight+=another.m_weight;
  13. return *this;
  14. }
  15. void Print()
  16. {
  17. cout << m_weight << endl;
  18. }
  19. private:
  20. int m_weight;
  21. };
  22. int main(void)
  23. {
  24. Goods A1(100);
  25. Goods A2(100);
  26. Goods A3(100);
  27. A1.Add(A2).Add(A3);
  28. A1.Print(); //300
  29. return 0;
  30. }

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读

    相关 c++笔记----this指针

    this指针 1. this是一个特殊的指针 1. 指向调用该成员函数的那个对象。 2. 是一个隐含每一个非静态成员函数的特殊指针。 1. 对象调

    相关 C++ this 指针

    C++ this 指针 在 C++ 中,每一个对象都能通过 `this` 指针来访问自己的地址。`this` 指针是所有成员函数的隐含参数。在成员函数内部,它可以用来指向

    相关 this指针

    对一个类的实例来说,你可以看到它的成员函数,成员变量,但是实例本身呢?this指针就是这样一个指针,它时时刻刻指向这个实例本身 (1)this只能在成员函数中使用,全局函数

    相关 关于this指针

    在每个成员函数中都包含一个特殊的指针,即this指针,它的名字是固定的。 this指针是指向当前对象的指针,它的值是当前被调用的成员函数所在对象的起始地址。 例1、

    相关 关于this指针

    在每个成员函数中都包含一个特殊的指针,即this指针,它的名字是固定的。 this指针是指向当前对象的指针,它的值是当前被调用的成员函数所在对象的起始地址。 例1、

    相关 c++ this 指针

    1. this指针的用处:   一个对象的this指针并不是对象本身的一部分,不会影响sizeof(对象)的结果。this作用域是在类内部,当在类的非静态成员函数中访问类的非

    相关 this指针

    文章目录 this指针是常量指针,不可修改 成员函数后加const 静态成员函数没有this指针 返回对象本身用 \

    相关 C++——this指针

     一 this指针的使用(成员函数中) 当通过一个对象调用成员函数时,编译器会把当前对象的地址传递给this指针;(this指针保存的是当前对象的地址) //thi