C++中如何实现虚函数?
C++ 中的虚函数用于创建基类指针的列表并调用衍生类的方法,而无需知道具体衍生类的对象。虚函数在运行时被延迟解析。
以下是 C++ 程序中虚函数的实现 -
示例
#include <iostream>
using namespace std;
class B {
public:
virtual void s() { //virtual function
cout<<" In Base \n";
}
};
class D: public B {
public:
void s() {
cout<<"In Derived \n";
}
};
int main(void) {
D d; // An object of class D
B *b= &d; // A pointer variable of type B* pointing to d
b->s(); // prints"D::s() called"
return 0;
}输出
In Derived
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP