this 指针

mac2022-06-30  23

// // 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

转载于:https://www.cnblogs.com/overlows/p/10802538.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)