对象各自的this指针指向各自对象的首地址,所以不同对象的this指针一定指向不同的内存地址
//Array.h
class Array
{
public:
Array(int len);
~Array();
Array& setLen(int len);
int getLen();
// Array printInfo();
Array& printInfo();//让它指直接返回指针
private:
int len;
};
//Array.cpp
#include "Array.h"
#include <iostream>
using namespace std ;
Array::Array(int len)
{
this -> len = len;
}
Array::~Array()
{
cout << "~Array()" << endl;
}
Array &Array::setLen(int len)
{
this -> len = len;
return *this;
}
int Array::getLen()
{
return len;
}
//注意这里的Array指的是返回此Array对象,不是返回数组
// Array Array::printInfo()
Array& Array::printInfo()
{
cout <<"pointer of this is " << this << endl << "len = " << len << endl;
return *this;//this本身是一个指针,加上*后就是一个对象
}
//demo.cpp
#include <iostream>
#include <stdlib.h>
#include "Array.cpp"
using namespace std;
int main()
{
Array arr1(10);
arr1.printInfo();
cout << "the address of arr1 is "<< &arr1 << endl;
// arr1.printInfo().setLen(5).printInfo();
//cout << "len = "<<arr1.getLen() << endl;
return 0 ;
}
参考链接:
http://www.cnblogs.com/kkdd-2013/p/5444355.html
http://eksea.com/