virtual在类中使用
如在多继承中(环状继承):
class D{......}; class B: public D{......}; class A: public D{......}; class C: public B, public A{.....};
这个继承会使D创建两个对象,要解决这个问题就可以使用虚拟继承格式:
class D{......}; class B: virtual public D{......}; class A: virtual public D{......}; class C: public B, public A{.....};
虚继承:在创建父类的时候(在创建对象的时候会创建一个虚表)。
#include <iostream> using namespace std; class D { public: D() { cout << "D()" << endl; } ~D() { cout << "~D()" << endl; } protected: int d; }; class B : virtual public D { public: B() { cout << "B()" << endl; } ~B() { cout << "~B()" << endl; } protected: int b; }; class A : virtual public D { public: A() { cout << "A()" << endl; } ~A() { cout << "~A()" << endl; } protected: int a; }; class C : public B, public A { public: C() { cout << "C()" << endl; } ~C() { cout << "~C()" << endl; } protected: int c; };
运行测试
int main() { /* the order of class constract with keyword virtual: D,B,A,C; otherwise: D,B,D,A,C; create class D twice; */ C c; cout << "sizeof(c): " << sizeof(c) << endl; return 0; }
测试结果
D() B() A() C() ~C() ~A() ~B() ~D()
virtual在函数中使用
类Base中加了virtual关键字的函数就是虚拟函数(例如下面例子中的函数print),于是在Base的派生类BaseSub中就可以通过重写虚拟函数来实现对基类虚拟函数的覆盖。
当基类Base的指针base_prt指向派生类BaseSub的对象时,对base_prt的print函数的调用实际上是调用了BaseSub的print函数而不是Base的print函数。
这是面向对象中的多态性的体现。
class Base { public: Base() { cout << "Base()" << endl; }; ~Base() { cout << "~Base()" << endl; }; virtual void paint() { cout << "paint Base" << endl; }; }; class BaseSub : public Base { public: BaseSub() { cout << "BaseSub()" << endl; }; ~BaseSub() { cout << "~BaseSub()" << endl; }; void paint() { cout << "paint BaseSub" << endl; }; };
测试代码
int main() { Base *base_prt = new BaseSub(); // call paint() in class BaseSub, because keyword virtual; base_prt->paint(); delete base_prt; return 0; }
运行结果
Base() BaseSub() paint BaseSub ~Base()
标签:BaseSub,......,c++,class,关键字,Base,virtual,public From: https://www.cnblogs.com/johnnyzhao/p/17034509.html