C++返回this对象的成员函数
返回this的引用#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct obj {
struct obj& returnThis() {
return *this;//this解引用后将会变为对象,对象赋给引用,则引用为这个对象的引用
}
int data;
};
int main(void) {
struct obj myObject;
myObject.data = 100;
struct obj& Object = myObject.returnThis();
Object.data = 200;
cout << myObject.data << endl;
return 0;
}
返回this指针
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct obj {
struct obj& returnThis() {
return *this;//this解引用后将会变为对象,对象赋给引用,则引用为这个对象的引用
//返回对象的引用
}
struct obj* returnthisP() {
return this;//返回this指针
}
int data;
};
int main(void) {
struct obj myObject;
myObject.data = 100;
struct obj& Object = myObject.returnThis();
Object.data = 200;
cout << myObject.data << endl;
struct obj* other = myObject.returnthisP();
other->data = 300;
cout << myObject.data << endl;
return 0;
}
文档来源:51CTO技术博客https://blog.51cto.com/u_15302296/3072247
页:
[1]