C++ 虚函数成员和纯虚函数

一般虚函数成员的声明语法是:

virtual 函数类型 函数名(形参表);

在类的定义使用virtual关键字来限定成员函数,虚函数声明只能出现在类定义中的函数原型声明中,而不能在成员函数实现的时候出现。

#include <iostream>

using namespace std;

class Base1{
    
    
	public:
		virtual void display() const;  // 虚函数 
};

void Base1::display() const{
    
    
	cout << "Base1::display()" << endl;
}

class Base2 : public Base1{
    
      // 定义派生类 
	public:
		void display() const;    // 覆盖基类的虚函数 
};  

void Base2::display() const{
    
    
	cout << "Base2::display()" << endl;
}

class Derived: public Base2{
    
      // 定义派生类 
	public:
		void display() const;  // 覆盖基类的虚函数 
};

void Derived::display() const{
    
      
	cout << "Derived::display()" << endl;
}

void fun(Base1 *ptr){
    
    
	ptr -> display();     
} 

int main(){
    
    
	Base1 *base1 = new Base1();
	Base2 *base2 = new Base2();
	Derived *derived = new Derived();
	
	fun(base1);
	fun(base2);
	fun(derived);
	
	delete derived;
	delete base2;
	delete base1;
	
	return 0;
	
}

运行过程中的多态需要满足3个条件,第一是类之间满足赋值兼容 规则,第二是要声明虚函数,第三是要由成员函数来调用或者是通过指针、引用来访问虚函数。如果是使用对象名来访问虚函数,则绑定在编译过程中就可以进行(静态绑定),而无须在运行过程中进行。


带有纯虚函数的类是抽象类,抽象类不能实例化,即不能定义一个抽象类的对象,但是可以定义一个抽象类的指针和引用。通过指针或引用,就可以指向并访问派生类的对象,进而访问派生类的成员,这种访问是具有多态特征的。

#include <iostream>

using namespace std;

class Base1{
    
    
	public:
		virtual void display() const = 0;  // 纯虚函数 
};

class Base2 : public Base1{
    
      // 定义派生类 
	public:
		void display() const;    // 覆盖基类的虚函数 
};  

void Base2::display() const{
    
    
	cout << "Base2::display()" << endl;
}

class Derived: public Base2{
    
      // 定义派生类 
	public:
		void display() const;  // 覆盖基类的虚函数 
};

void Derived::display() const{
    
      
	cout << "Derived::display()" << endl;
}

void fun(Base1 *ptr){
    
    
	ptr -> display();     
} 

int main(){
    
    
	Base2 *base2 = new Base2();
	Derived *derived = new Derived();
	
	fun(base2);
	fun(derived);
	
	delete derived;
	delete base2;
	
	return 0;
	
}

猜你喜欢

转载自blog.csdn.net/qq_44989881/article/details/112301375