C++之虛函數、多態、抽象類


虛函數

語法:
1 父類------有了virtual,則 子類 纔可能 使用到  多態
2 子類中的 virtual可以省--------但最好別省
3 必須使用new ,給 父類地址變量 賦值,才能用到 多態。


//代碼:
int main()
{
	CStudent_college stu1(1001,"zhangsan","計算機系","軟件專業");
	CStudent_pupil stu2(901,"xiaoming","中隊長");


	stu1.print_student();
	stu2.print_student();


	//CStudent_college *pstu1=new CStudent_college(1001,"zhangsan","計算機系","軟件專業");
	CStudent *pstu1=new CStudent_college(1001,"zhangsan","計算機系","軟件專業");
	CStudent *pstu2=new CStudent_pupil(901,"xiaoming","中隊長");


	pstu1->print_student();   //virtual
	pstu2->print_student();


	return 0;
}




抽象類

舉例:


有1類--------人類
按道理,不應該 能建立 1個 人類的 對象
但這種類,應該很適合 作爲 父類


從語法上如何解決?
利用了 虛函數---------在h文件中,在某個成員函數的前面 加 virtual     最後加=0   
該類 編程了 抽象類


如果有1個子類,要繼承 抽象類(父類):
默認情況下,子類 也是 抽象類   --------  如何,子類中實現了 抽象類中的 所有 純虛函數,子類纔不會是 抽象類

代碼:抽象類---------和它的派生類



//Person.h-----抽象類
class CPerson  
{
public:
	char *name;
	int age;


	CPerson();
	CPerson(char *name,int age);
	virtual ~CPerson();
	virtual void print_person()=0;
};			




//Person.cpp
// Person.cpp: implementation of the CPerson class.
//
//////////////////////////////////////////////////////////////////////
#include <iostream>
#include "Person.h"


using namespace std;


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////


CPerson::CPerson()
{


}


CPerson::~CPerson()
{


}


CPerson::CPerson(char *name,int age)
{
	this->name=new char[strlen(name)+1];
	strcpy(this->name,name);
	this->age=age;
}




/*
void CPerson::print_person()
{
	cout<<"name is "<<name<<"  age is "<<age<<endl;
	return;
}*/




//Worker.h----抽象類的 派生類
#include "Person.h"


class CWorker : public CPerson  
{
public:
	CWorker();
	virtual ~CWorker();
	void print_person();
};






//Worker.cpp
// Worker.cpp: implementation of the CWorker class.
//
//////////////////////////////////////////////////////////////////////


#include "Worker.h"


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////


CWorker::CWorker()
{


}


CWorker::~CWorker()
{


}
void CWorker::print_person()
{
	;
}




//main.cpp
#include "Student_college.h"
#include "Student_pupil.h"
#include "Student.h"
#include "Worker.h"


int main()
{
	/*
	CStudent_college stu1(1001,"zhangsan","計算機系","軟件專業");
	CStudent_pupil stu2(901,"xiaoming","中隊長");


	//stu1.print_student();
	//stu2.print_student();


	//CStudent_college *pstu1=new CStudent_college(1001,"zhangsan","計算機系","軟件專業");
	CStudent *pstu1=new CStudent_college(1001,"zhangsan","計算機系","軟件專業");
	CStudent *pstu2=new CStudent_pupil(901,"xiaoming","中隊長");


	pstu1->print_student();   //如果不使用virtual函數,則系統默認 靜態綁定;加了虛函數,就是動態綁定---多態
	pstu2->print_student();*/
	//CPerson per1("zhangsan",21);
	//per1.print_person();
	CWorker worker1;
	return 0;
}		


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章