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
posted @ 2019-05-02 16:04  芷恬  阅读(180)  评论(0编辑  收藏  举报