欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

this 指针

程序员文章站 2023-10-31 21:39:04
``` // // main.cpp // this指针 // // Created by mac on 2019/5/2. // Copyright © 2019年 mac. All rights reserved. // 默认情况下,编译器为类的每个成员函数提供了一个隐式形参,该隐式形参成为th ......
//
//  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