重载、重写(覆盖)、隐藏(重定义)

1 要求和区分

1)重载要求:函数名相同,参数不同(个数、类型)、常函数也可以作为重载判断。注意返回值不是重载的判断标准。

2)重写(即覆盖)要求:要求基类函数为虚函数,且基类函数和派生类函数名、参数等相同。

3)隐藏(即重定义)要求:子类重新定义父类中有相同名称的非虚函数(参数列表可以不同)。

4)重写和隐藏都是发生在基类和子类中。

 

2 重载代码演示

#include "stdafx.h"
#include 


/*-------------------------
//   重载
-------------------------*/ 
class Overload{
public:
	Overload(){};
	~Overload(){};
	void displayNumType(int) { std::cout << " number is int " << std::endl; }
	void displayNumType(short) { std::cout << " number is short " << std::endl; }
	void displayNumType(double) { std::cout << " number is double " << std::endl; }
	void displayNumType(int, double) { std::cout << " number1 is int, number2 is double " << std::endl; }
	void displayNumType(double, int) { std::cout << " number1 is double, number2 is int " << std::endl; }
	void displayNumType(int) const { std::cout << " number is int and function is const " << std::endl; }
};


int main(){

	Overload r;
	int num1 = 5;
	short num2 = 5;
	double num3 = 5;
	r.displayNumType(num1);
	r.displayNumType(num2);
	r.displayNumType(num3);
	r.displayNumType(num1, num3);
	r.displayNumType(num3, num1);
	
	const Overload r1;
	r1.displayNumType(num1);

	return 0;
}


结果显示:
 number is int
 number is short
 number is double
 number1 is int, number2 is double
 number1 is double, number2 is int
 number is int and function is const
请按任意键继续. . .

 

3 覆盖代码演示

#include "stdafx.h"
#include 


/*-------------------------
//   覆盖
-------------------------*/
class A{
public:
	virtual void display() { std::cout << "This is Base" << std::endl; }
};


class B : public A{
public:
	void display() { std::cout << "This is derived" << std::endl; }
	void display1() { std::cout << "This is derived" << std::endl; }
};


int main(){
	A *a = new B;
	B b;
	a->display();
	//a->display1();
	b.display();
	b.display1();
}


结果显示:
This is derived
This is derived
This is derived
请按任意键继续. . .

至于为什么a->display1() 会出现错误?

因为display1()不是A的成员。

从上面的代码可以看出,覆盖(重写)主要是虚函数多态时使用,而重载也是多态的一种,两者不一样!

 

4 隐藏代码演示

#include "stdafx.h"
#include 


/*-------------------------
//   隐藏
-------------------------*/
class A{
public:
	void display() { std::cout << "This is Base" << std::endl; }
};


class B : public A{
public:
	void display() { std::cout << "This is derived" << std::endl; }
};


int main(){
	A a;
	B b;
	a.display();
	b.display();
	return 0;
}


结果显示:
This is Base
This is derived
请按任意键继续. . .


备注:如果将B中的display注释掉,结果显示为:
This is Base
This is derived

 

你可能感兴趣的:(C/C++)