Learning C ++ object-oriented (3) polymorphism ---

Here Insert Picture Description


|| inheritance applies to the presence of similar properties or behavior

Similar || polymorphisms exist in the same applies to the behavior (behavioral details but varied) when

|| c ++, the class and subclass between the parent does not require a cast parent class object as a parameter may be received by a subclass object parameters parent class object

void test02(Animal &animal) {  
	animal.speak();
}

Dog dog;
test02(dog);

|| polymorphic use, we will conduct a A diverse, but use is a function name, in order to allow the specified object A call their behavior, we need to pay attention to the problem address binding function

|| virtual functions
using the virtual function may be configured such that a virtual functionFunction address late binding

Functions related to the above test02 Early binding function addressThe problem
calls the member functions in the local function, the function address occurs early binding
can cause actual behavior of the object call error

	虚函数语法:virtual 返回值类型 函数名 (参数列表){} ;

Polymorphic implementation conditions ||

- sub-class "override" "virtual" parent - the
parent class: This member function to virtual function, subclasses: override this member function

|| polymorphic use

- parent pointers or references to sub-class objects -
Principle: In this case virtual function pointers will point to the animal vtable override the subclass object
(typically a common function can be constructed, which is the parent class pointer parameter, call when multi-state)

Cat cat;
Animal &animal = cat

|| pure virtual function

In the multi-state, the realization of virtual functions is usually the parent class is meaningless, the main contents are calling overridden subclass
therefore virtual function can be changed to a pure virtual function

	纯虚函数语法:virtual 返回值类型 函数名 (参数列表)= 0 ;

|| virtual destructor

When using multi-state, if there is a subclass attributes to open heap, then parent pointer is not released when the code calls to the destructor subclass
solutions: parent class destructor changed or a virtual destructors virtual destructors

	虚析构语法:
	virtual ~类名(){}

Pure virtual destructor ||

	纯虚析构语法:
	virtual ~类名() = 0;
	类名::~类名(){}

	与纯虚函数不同的是,函数=0后,还需要补充其空实现

|| abstract class
as the class with a pure virtual function (including pure virtual destructor), this class is called an abstract class

	抽象类特点
		*无法实例化对象
		*子类必须重写抽象类中的纯虚函数,否则也属于抽象类
Published 24 original articles · won praise 40 · views 3946

Guess you like

Origin blog.csdn.net/a13352912632/article/details/104185394