类继承中的this指针

结合如下列子即可:

//	成员函数处理不同对象的访问,关键在于成员函数有一个隐藏参数,即this指针

#include "stdafx.h"
#include "cstdio"
#include "iostream"
using namespace std;

class CAnimal
{
private:
	int m_nType;
public:
	void SetType(int type)  //相当于 void SetType(int type,(CAnimal*)this)
	{
		m_nType = type;		//相当于 this->m_nType = type
		cout << "Type is " << m_nType << endl;
	}
};
class Cbird : public CAnimal
{
public:
	void Cry()
	{
	}
};

int main(int argc, char* argv[])
{
	Cbird bird1,bird2;
	
	bird1.SetType(1); // 相当于 Cbird::SetType(1,(Cbird*)&bird1);即CAnimal::SetType(1,(Cbird*)&bird1);
	bird2.SetType(2); // 相当于 Cbird::SetType(2,(Cbird*)&bird2);即CAnimal::SetType(2,(Cbird*)&bird2);	

	return 0;
}


你可能感兴趣的:(c++)