this 指針

//
//  main.cpp
//  this指針
//
//  Created by mac on 2019/5/2.
//  Copyright © 2019年 mac. All rights reserved.
//  默認狀況下,編譯器爲類的每一個成員函數提供了一個隱式形參,該隱式形參成爲this

#include <iostream>

using namespace std;

class Example{
private:
    int x;
public:
    Example(int a){
        this->x=a;
    }
    void setValue(int);
    void printAddressAndValue()const;
    
};

void Example::setValue(int a){
    this->x=a;
}

void Example::printAddressAndValue()const{
    cout<<"The object at address "<<this<<" has "<<"value "<<(*this).x<<endl;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    Example obj1(10),obj2(20);
    cout<<"Address of objects are "<<&obj1<<" and "<<&obj2<<endl;
    obj1.printAddressAndValue();
    obj2.printAddressAndValue();
    return 0;
}

運行結果

Address of objects are 0x7ffeefbff578 and 0x7ffeefbff570
The object at address 0x7ffeefbff578 has value 10
The object at address 0x7ffeefbff570 has value 20
Program ended with exit code: 0
相關文章
相關標籤/搜索