美文网首页
C++ - this 指针

C++ - this 指针

作者: Mitchell | 来源:发表于2016-01-15 16:51 被阅读122次
  • 从 C++ 程序到 C 程序的翻译
//C++
class CCar{
    public:
          int price;
          void SerPrice(int p);
};
void CCar::SetPrice(int p){price = p;}
int main(){
      CCar car;
      car.SetPrice(20000);
      return 0;
}
//C
struct CCar {
      int price;
};
void SetPrice(struct CCar*this int p)
{ this->price = p;}
int main(){
   struct CCar car;
   SetPrice(&car,20000);
    return 0;
}
  • 作用就是指向成员函数所作用的对象
class Complex{
    public:
        double real,image;
        void Print(){cout<<real<<","<<imag;}
        Complex(double r,double i):real(r),image(i){    }
        Complex AddOne(){
            this->real++;//等价于 real++
            this->Print();//等价于 Print
            return * this;//返回作用的对象
        }
};
int main(){
    Complex c1(1,1),c2(0,0);
    c2 = c1.AddOne();
    return 0;
}
  • this 指针作用
//这个函数不会出错 
classs A
{
        int i;
    public:
              void Hello(){cout<<"hello"<<endl;}
};->void Hello(A * this){out<<"hello"<<endl;}
int main()
{
      A * p = NULL;
      p->Hello();->Hello(p);
}//输出: hello
//这样就会出错
classs A
{
        int i;
    public:
              void Hello(){cout<<"i"<<"hello"<<endl;}
};->void Hello(A * this){out<<this->i<<"hello"<<endl;}
//this 若为 NULL,则出错!!
int main()
{
      A * p = NULL;
      p->Hello();->Hello(p);
}//输出: hello
  • 在类的非静态成员函数中,C++ 的函数都会默认多出一个参数就是 this 指针,指向的是他所对应的对象。
  • 注意
    • 静态成员函数中不能使用this 指针!
    • 因为静态成员函数并不具体作用于某个对象!
    • 因此,静态成员函数的真实的参数个数,就是程序中写出的参数个数!

相关文章

  • C++知识点

    C++基本方法: C++ memcpy C++基本特性: C++引用(vs指针) C++指针 C++封装: 将...

  • C++ 指针常量、常量指针和常指针常量

    参考:C++ 指针常量、常量指针和常指针常量

  • Java基础

    Java和C++的区别?a. Java没有指针。c++可以通过指针直接操作内存,但这个动作是危险的,指针引起的操作...

  • Jna send pointer pointer to c++

    目的: 有这样一个需求,java通过jna传递指针数组给c++,或者指针的指针 解决方案: c++ : 声明 vo...

  • C++ 指向类的指针

    原文地址:C++ 指向类的指针 一个指向 C++ 类的指针与指向结构的指针类似,访问指向类的指针的成员,需要使用成...

  • C++基础

    C++ 值传递、指针传递、引用传递详解C++中引用传递与指针传递区别 引用传递和指针传递的区别 引用的规则:(1)...

  • C++函数指针和Swift的函数对象

    C++函数指针和Swift的函数对象 在C++中学习函数指针式非常痛苦的事情,而在Swift里面学习函数指针则是非...

  • [C++之旅] 16 对象指针/对象成员指针/this指针

    [C++之旅] 16 对象指针/对象成员指针/this指针 一、对象指针 对象指针指向堆中地址 对象指针指向栈中地...

  • C++ 、java 和 C# 的区别

    一、基础类型 c++: ** java:** C#: 二、指针 1.java 是没有指针这个概念,c++ 和 c#...

  • 静心学习之路(7)——C++干架用知识

    善用书籍后自带的单词索引 指针、引用、数组、内存。《C++ Primer 5th》2.3.2——指针《C++ Pr...

网友评论

      本文标题:C++ - this 指针

      本文链接:https://www.haomeiwen.com/subject/igyhkttx.html