zoukankan      html  css  js  c++  java
  • this指针

    我们都知道,C++是以C语言为基础发展而成的,最早的C++编译器实际上是现将C++程序翻译成
     C语言程序再进行编译的。但C语言中并没有成员函数这一概念,只有全局函数。那么成员函数
     是如何被翻译的呢?答案是引入this指针。
       
     this指针:
            实际上非静态成员函数的形参上实际上隐藏了一个参数,即this指针。this指针指向了成
      员函数作用的对象,在成员函数执行的过程中,正是通过this指针才能找到对象所在的地
      址,从而找到所有类中非静态变量的地址。
     
         C++规定,在非静态成员函数内部可以直接使用this关键字,,this就代表指向该函数所作
      用对象的指针。
      
      由于静态成员函数并不是作用于某个对象,所以在其内部不能使用this指针。

    #include <iostream>
    
    using namespace std;
    
    class Complex{
        public:
            double real, imag;
            Complex(double r, double i):real(r), imag(i){
            }
            Complex AddOne(){
                this->real++;
                return *this;
            }
    };
    
    int main()
    {
        Complex c1(1, 1), c2(0, 0);
        c2 = c1.AddOne();
        cout << c1.real << "," << c1.imag << endl;
        cout << c2.real << "," << c2.imag << endl;
        cout << &c1 << ", " << &c2 << endl;
        
        return 0;
    }
  • 相关阅读:
    Leetcode: Total Hamming Distance
    Leetcode: Hamming Distance
    Leetcode: Valid Word Square
    Leetcode: Sentence Screen Fitting
    Leetcode: Minimum Unique Word Abbreviation
    Leetcode: Design Phone Directory
    Leetcode: Valid Word Abbreviation
    Leetcode: Range Addition
    Leetcode: Find Leaves of Binary Tree
    Leetcode: Design Hit Counter
  • 原文地址:https://www.cnblogs.com/lnlin/p/7587993.html
Copyright © 2011-2022 走看看