本文内容摘录自:从零开始学C++程序设计,仅作为入门使用。
在创建类的对象的同时,对象会自动创建属于它自己的指针,在引用时可以用“this”指令来表示,this指针为指向对象本身的指针,指向内存中存储该对象的地址。
通过this指针可以存取到该类的数据成员和成员函数,语法如下所示:
this->数据成员
(*this).数据成员
范例程序用于示范当函数返回值为类对象时的方法。
#include <iostream>
using namespace std;
class Square //定义Square类
{
int a;
public:
Square(int n) {
a = n*n;
}
Square squ_sum(Square b) {
this->a = this->a + b.a;
return *this;
}
int show_data() {
cout<<(*this).a<<endl;
return 0;
}
};
int main()
{
int n1, n2;
cout<<"输入第一个数:";
cin>>n1;
cout<<"输入第二个数:";
cin>>n2;
Square first(n1), second(n2), third(0);
third = first.squ_sum(second);
third.show_data();
return 0;
}