1. 程式人生 > >多態——virtual

多態——virtual

過程 nbsp 作用 基類 註意 spa name 現在 lib

作用:解決當使用基類的指針指向派生類的對象並調用派生類中與基類同名的成員函數時會出錯(只能訪問到基類中的同名的成員函數)的問題,從而實現運行過程的多態

不加virtual

 1 #include<iostream>
 2 #include<stdlib.h>
 3 using namespace std;
 4 
 5 class Base {
 6 private:
 7     int mA;
 8     int mB;
 9 public:
10     Base(int a, int b)
11     {
12         mA = a;
13         mB = b;
14 } 15 void ShowMem() 16 { 17 cout << mA << " " << mB << endl; 18 } 19 }; 20 21 class Derived:public Base { 22 private: 23 int mA; 24 int mB; 25 int mC; 26 public: 27 Derived(int a, int b, int c):Base(a,b) 28 { 29 mA = a;
30 mB = b; 31 mC = c; 32 } 33 void ShowMem() 34 { 35 cout << mA << " " << mB << " " << mC << endl; 36 } 37 }; 38 39 void test(Base &temp) 40 { 41 temp.ShowMem(); 42 } 43 44 int main() 45 { 46 Base b(1,2); 47 b.ShowMem();
48 Derived d(3, 4, 5); 49 d.ShowMem(); 50 51 test(b); 52 test(d); 53 54 system("PAUSE"); 55 return 0; 56 }

輸出:

技術分享

加virtual

#include<iostream>
#include<stdlib.h>
using namespace std;

class Base {
private:
	int mA;
	int mB;
public:
	Base(int a, int b)
	{
		mA = a;
		mB = b;
	}
	virtual void ShowMem()
	{
		cout << mA << "  " << mB << endl;
	}
};

class Derived:public Base {
private:
	int mA;
	int mB;
	int mC;
public:
	Derived(int a, int b, int c):Base(a,b)
	{
		mA = a;
		mB = b;
		mC = c;
	}
	void ShowMem()
	{
		cout << mA << "  " << mB << "  " << mC << endl;
	}
};

void test(Base &temp)
{
	temp.ShowMem();
}

int main()
{
	Base b(1,2);
	b.ShowMem();
	Derived d(3, 4, 5);
	d.ShowMem();

	test(b);
	test(d);

	system("PAUSE");
	return 0;
}
輸出:
 
技術分享

使用方法

virtual 返回類型 函數名(形參表)

  註意:只能出現在聲明中

實現條件:
  • 類之間滿足類的賦值兼容規則
  • 聲明虛函數
  • 有成員函數來調用或者是通過指針,引用來訪問同名函數

多態——virtual