Virtual Function in C++

//  ---------https://www.geeksforgeeks.org/virtual-function-cpp/

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class base{
public:
	virtual void print(){
		cout<<"print base class"<<endl;
	}
	void show(){
		cout<<"show base class"<<endl;
	}
};
class derive:public base{
public:
	void print(){
		cout<<"print derived class"<<endl;
	}
	void show(){
		cout<<"show derived class"<<endl;
	}
};

int main(int argc, char const *argv[])
{
	base *bptr;
	derive d;
	bptr= &d;
	bptr->print();//Virtual function,所以调用 derived class

	bptr->show();//non-virtual function 调用base class
	return 0;
}

输出:

A virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class.When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

猜你喜欢

转载自blog.csdn.net/qq_32095699/article/details/81237836