在我定义其函数之前,编译器假定子 class 是虚拟的

Compiler assumes child class is virtual before I define its functions

这是一个示例程序,演示了我在大型程序中遇到的问题。

基本上,我在 .h 文件中有父子 class 的声明。因为父classA是虚的,编译器就假定子B也是虚的,不让我在.cpp文件中定义它的函数。错误说:

candidate is: virtual void B::print()

但我不希望它是虚拟的。

example.h 文件:

class A{   
public:
    int x;
    A();
    virtual void print();
};

class B : public A {
public:
    void print(){};
};

example.cpp 文件:

#include "example.h"
#include <iostream>

using namespace std;

A::A(){ x = 10; }

B::print(){ cout << x << endl; }

main.cpp 文件:

#include "example.h"

using namespace std;

int main()
{
    B b;
    b.print();

    return 0;
}

有什么方法可以解决这个问题,同时保持 3 个独立的文件?

一旦方法被显式标记为 virtual,它在派生 类 中始终是虚拟的,即使它在那些 类 中没有被显式标记为 virtual ].没有办法改变它。

错误的原因是您有 2 个相互竞争且不兼容的 B::print() 定义 - 一个在 example.h 中内联,一个在 example.cpp 中。您需要从 example.h:

中删除内联定义
class B : public A {
public:
    void print(); // <-- no braces here!
};

此外,example.cpp 中的定义缺少 return 类型:

void B::print() { cout << x << endl; } // <-- add 'void' here!