首页 > 其他 > 详细

this 指针

时间:2019-05-02 16:42:41      阅读:129      评论:0      收藏:0      [点我收藏+]
//
//  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

this 指针

原文:https://www.cnblogs.com/overlows/p/10802538.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!