多态——virtual

作用:解决当使用基类的指针指向派生类的对象并调用派生类中与基类同名的成员函数时会出错(只能访问到基类中的同名的成员函数)的问题,从而实现运行过程的多态

不加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 返回类型 函数名(形参表)

  注意:只能出现在声明中

实现条件:
  • 类之间满足类的赋值兼容规则
  • 声明虚函数
  • 有成员函数来调用或者是通过指针,引用来访问同名函数
原文地址:https://www.cnblogs.com/yueruifeng/p/6914062.html