【问题标题】:Compiler assumes child class is virtual before I define its functions在我定义子类的函数之前,编译器假定子类是虚拟的
【发布时间】:2021-02-23 01:54:10
【问题描述】:

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

基本上,我在.h 文件中有父类和子类的声明。因为父类A 是虚拟的,所以编译器假定子类B 也是虚拟的,不会让我在.cpp 文件中定义它的功能。错误说:

候选人是: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 个单独的文件?

【问题讨论】:

  • int x;privateB 看不到。
  • 即使我删除花括号并将 x 公开,问题仍然存在。我应该编辑问题中的那些,因为我忽略了它们。

标签: c++ inheritance virtual-functions


【解决方案1】:

一旦一个方法被显式标记为virtual,它在派生类中总是虚拟的,即使它没有在这些类中显式标记为virtual。没有办法改变它。

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

class B : public A {
public:
    void print(); // <-- no braces here!
};

另外,example.cpp 中的定义缺少返回类型:

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

【讨论】:

  • 我以为我只需要在声明中编写返回类型而不是定义,这就是它不起作用的原因。牙套只是一个俯瞰。现在可以使用了,谢谢!
  • @GeorgeT "我以为我只需要在声明中写返回类型而不是定义" - 不。声明和定义都必须具有匹配的返回类型、调用约定和参数类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多