c++虛函數的學習

1.虛函數

#include<iostream.h>
 
class Base
{
public:
	void print()
	{
		cout<<"Base"<<endl;
	}
};
 
class Son:public Base
{
public:
	void print()
	{
		cout<<"Son"<<endl;
	}
};
 
void fun(Base *obj)
{
	obj->print();
}
 
int main()
{
	Base base;
	Son son;
	fun(&base);
	fun(&son);
	return 0;
}

類Base和Son中都有print方法,Son繼承Base類。在主函數中分別建立Base和Son的對象,在fun函數中調用對象的print()方法。運行結果如下

從結果中可以看出不論傳的是父對象的地址還是子對象的地址,最終調用的都是父對象的print()方法。如果希望傳父對象時調用父對象print()方法,傳子對象時調用子對象的print()方法。則只需要將父類的print方法聲明成虛函數就行。virtual void print(){}。

2.純虛函數

(1)純虛函數的定義

virtual 返回類型 函數名 (<參數>)=0;
 

#include<iostream.h>
 
class Shape
{
public:
	virtual void show()=0;
};
 
class Circle:public Shape
{
public:
	void show()
	{
		cout<<"Circle"<<endl;
	}
};
 
class Rect:public Shape
{
public:
	void show()
	{
		cout<<"Rect"<<endl;
	}
};
 
void fun(Shape *shape)
{
	shape->show();
}
 
int main()
{
	//Shape  s;//純虛函數的類不能創建對象
	Circle circle;
	Rect   rect;
	fun(&circle);
	fun(&rect);
	return 0;
}

 

有純虛函數的類不能創建對象。在基類中只作方法的聲明,具體的實現要由其子類來實現。

 

轉:https://blog.csdn.net/mxway/article/details/9672237

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