【问题标题】:Figuring out what makes a C++ class abstract in VS2008弄清楚是什么让 VS2008 中的 C++ 类抽象
【发布时间】:2010-04-26 14:54:46
【问题描述】:

我正在使用 VS2008 构建一个普通的旧 C++ 程序(不是 C++/CLI)。我有一个抽象基类和一个非抽象派生类,并构建它:

Base* obj;
obj = new Derived();

失败并出现错误“'Derived':无法实例化抽象类”。 (然而,值得注意的是,如果我将光标悬停在 Base 上,VS 会弹出一个工具提示说“类 Base abstract”,但悬停在 Derived 上只会说“类派生”(没有“摘要"))。

这些类的定义相当大,我想避免手动检查每个方法是否已被覆盖。 VS可以以某种方式为我做这件事吗?关于确定类定义中使其抽象化的确切部分的任何一般提示?

【问题讨论】:

    标签: c++ visual-studio visual-studio-2008 abstract-class


    【解决方案1】:

    编译器应该在错误信息中告诉你。以下:

    struct base
    {
        virtual void foo(void) = 0;
        virtual void bar(void) = 0;
    };
    
    struct derived : base
    {
        virtual void foo(void){}
    };
    
    int main(void)
    {
        derived d;
    }
    

    生产:

    错误 C2259:“派生”:无法实例化抽象类
    由于以下成员:
    'void base::bar(void)' : 是抽象的
    见'base::bar'的声明

    动态分配也是如此。

    【讨论】:

    • 确实,我忘了检查输出窗口(再次)。冒犯的方法已被发现,并因其不守规矩的行为而受到谴责。 :)
    【解决方案2】:

    不,我不相信 VS 开箱即用。 请参阅 GMan 的回答。

    另一方面,如果您有一个太大的基类,您无法快速检查它的虚方法,您可能需要考虑拆分该类。

    【讨论】:

      【解决方案3】:

      GMan 所说的。加上使用更好的编译器:-) 使用 g++,错误是:

      ab.cpp: In function 'int main()':
      ab.cpp:14: error: cannot declare variable 'd' to be of abstract type 'derived'
      ab.cpp:8: note:   because the following virtual functions are pure within 'derived':
      ab.cpp:4: note:         virtual void base::bar()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-01
        • 2014-05-15
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多