构造,析构,覆盖,重载,隐藏

来源:互联网 发布:录像软件bandicam 编辑:程序博客网 时间:2024/05/17 09:16
/// @file main.cpp/// @brief 构造,析构,覆盖,重载,隐藏#include <iostream>using namespace std;#include "myTemplate.h"class A1 {public:    A1() {        cout << "A1::A1" << endl;}    virtual void f(float x) {        cout << "A1::f(float)" << x << endl;}};class A2 {public:    A2() {        cout << "A2::A2" << endl;}    virtual void g(float x) {        cout << "A2::g(float)" << x << endl;}    void h(float x) {        cout << "A2::h(float)" << x << endl;}};template<typename TA2, typename TA1>class B : public TA1, public TA2 {public:    B() {        cout << "B::B" << endl;}    virtual void f(float x) {        cout << "B::f(float)" << x << endl;}    void g(int x) {        cout << "B::g(int)" << x << endl;}    virtual void h(float x) {        cout << "B::h(float)" << x << endl;}};/**c++ 继承机制中,对于函数调用,存在覆盖,重载,隐藏3种情况覆盖 : 不同作用域(子类和父类), 对于同样的虚函数,    在本实例虚表中覆盖父类虚函数重载 : 相同作用域(本类)中, 相同的函数名, 不同的参数类型或不同的参数个数,    在本类中的多个函数实现隐藏 : 不同的作用域(子类和父类), 非虚函数, 对于同名函数(参数个数相同)    在子类中,隐藏父类的实现*/int main(int argc, char* argv[]) {    /// 类实例构造顺序 : 基类,类成员变量,本类    B<A2,A1> theB; ///< B从A1,A2多继承    /// 实例的虚表, 只有多继承有多个虚表    /// 单继承只有本类的1个虚表    /// A1虚表    /// A1::f(float x)    /// ----------    /// A2虚表    /// g(float x)    /// ----------    /// theB虚表:    /// B::f(float x)    /// A2::g(float x)    /// B::h(float x)    /** run result    "A1::A1"    "A2::A2"    "B::B"    */    A1* pA = &theB;    B<A2,A1>* pb = &theB;    /// theB 覆盖了虚函数表父类(A1,A2)的虚表,    /// 如果用基类指针操作, 如果不强转,    ///     执行的虚函数都是自己的    ///     执行的非虚函数都是按照隐藏处理    pA->f(3.14f);    /**     "B::f(float)3.14"    */    printf("");    // pA->g(3.14f); ///< error C2039: 'g' : is not a member of 'A1'    /// 因为没有A1没有A1::g(flaot), 只有A2有A2::g(float)    /// A2::g 是 A2虚表中第一个虚函数    /// B::f 是B虚表中第一个虚函数    /// 强转之后, 执行的是theB中第一个虚函数f(float)    /// 所以, 强转类指针到基类,执行基类不存在的虚函数或函数,不正确    /// 如果真要执行类实例的基类虚函数,可以指定作用域    /// 而不能强转    pb->A2::g(3.14f); ///< ok    /**    A2::g(float)3.14    */    ((A2*)pA)->g(3.14f); ///< error    /**     /// 执行g(float), 只存在A2::g(float), 会执行A2:g    "B::f(float)3.14"          */        printf("");    pb->g(3.14f);    /**    /// 执行theB的非虚函数B::g(int)    /// 通过试验,可以看出隐藏优先级 > 覆盖优先级    /// 如果子类中有非虚函数可以执行, 不会去执行父类的虚函数    "B::g(int)3"    */    /// 如果要执行theB虚表中的A2::g(float x), 要指定作用域    pb->A2::g(3.14f);    /**    A2::g(float)3.14    */    printf("");    ((A2*)pA)->h(3.14f);    /** 指定了作用域 A2::, 执行的非虚函数A2::h    A2::h(float)3.14    */    printf("");    pb->h(3.14f);    /** 执行的虚函数, 隐藏,执行的是B:h    B::h(float)3.14    */    /** run result    A1::A1    A2::A2    B::B    B::f(float)3.14    A2::g(float)3.14    B::f(float)3.14    B::g(int)3    A2::g(float)3.14    A2::h(float)3.14    B::h(float)3.14    */    printf("");    return 0;}

0 0
原创粉丝点击