【问题标题】:C++ Virtual function in nested class [duplicate]嵌套类中的C ++虚函数[重复]
【发布时间】:2021-12-30 13:55:59
【问题描述】:

#include <iostream>

class  A
{

public:
    A(/* args */){};
    virtual void p(){std::cout << "A\n";}
};

class  B : public A
{

public:
    B(/* args */){};
};

class  C : public B
{

public:
    C(/* args */){};
    void p() override{std::cout << "C\n";}
};

int main(int argc, char const *argv[])
{
    B test = C();
    C test2 = C();


    test.p();
    test2.p();
    return 0;
}

目前它打印: 一种 C

我想像'test'变量一样将C保存为B形式;但是调用函数的覆盖版本,现在它调用基版本。

【问题讨论】:

    标签: c++ inheritance virtual


    【解决方案1】:

    找到了这个解决方案。

    int main(int argc, char const *argv[])
    {
        B *test = new C();
        C test2 = C();
    
    
        test->p();
        test2.p();
        return 0;
    }
    

    【讨论】:

    • 这是正确的,但它需要解释它的工作原理和原因,否则大多数人都会从中获得一个提高复制和粘贴技能的机会。
    猜你喜欢
    • 2021-05-19
    • 2021-07-22
    • 2011-08-15
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多