首页  

C++ this 指针     所属分类 c 浏览量 634
在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址
this 指针是所有成员函数的隐含参数
在成员函数内部,可以用来指向调用对象
友元函数没有 this 指针,因为友元不是类的成员
只有成员函数才有 this 指针


#include "iostream"

class A{
  int value;
  public:
    A(int value){
      this->value=value;      
    }
    void setValue(int value){
      this->value = value;
    }
    int getValue(){
      return this->value;
    }
};

int main(){
  A a1(1);
  A a2{2};
  std::cout <<  a1.getValue() << std::endl;
  std::cout <<  a2.getValue() << std::endl;
  a1.setValue(3);
  std::cout <<  a1.getValue() << std::endl;
  
  a2 = a1;
  std::cout <<  a2.getValue() << std::endl;
  
  A a3(a1);
  std::cout <<  a3.getValue() << std::endl;

  return 0;
}

上一篇     下一篇
C++ 花括号和括号初始化的区别

C++面向对象知识点

c++构造函数

c语言中常见的内存错误

c++运算符优先级和结合性

编译时指定宏参数