C++中派生类中的虚函数

虚函数是由派生类重写的基类的成员函数。当使用基类的指针或引用引用派生类对象时,可以为该对象调用虚拟函数,并让它运行派生类版本的函数。

null

在C++中,一旦一个成员函数在基类中声明为虚函数,它就在从该基类派生的每个类中变成虚拟的。换句话说,在声明虚拟基类函数的重新定义版本时,不必在派生类中使用关键字virtual。

例如,以下程序在B::fun()自动变为虚拟时打印“C::fun()调用”。

CPP

// CPP Program to demonstrate Virtual
// functions in derived classes
#include <iostream>
using namespace std;
class A {
public :
virtual void fun() { cout << " A::fun() called " ; }
};
class B : public A {
public :
void fun() { cout << " B::fun() called " ; }
};
class C : public B {
public :
void fun() { cout << " C::fun() called " ; }
};
int main()
{
C c; // An object of class C
B* b = &c; // A pointer of type B* pointing to c
b->fun(); // this line prints "C::fun() called"
getchar ();
return 0;
}


输出

 C::fun() called 

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享