为什么必须从继承的类中重新声明虚函数? [英] Why must I re-declare a virtual function from an inherited class?

查看:96
本文介绍了为什么必须从继承的类中重新声明虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的C ++程序,并且很难理解我遇到的编译器错误.该问题是由于我试图从基类创建派生类而引起的.我在下面以相同的结构发布了我的代码,但更改了名称.

I'm working on a simple C++ program and am having a difficult time understanding a compiler error I was getting. The issue was caused by me attempting to create a derived class from a base class. I've posted my code below with the same structure but have changed the names.

BaseClass.h

#ifndef BASECLASS_H
#define BASECLASS_H

class BaseClass {

    public:
        BaseClass(void);

        virtual int method1(void) = 0;
        virtual int method2(void) = 0;
        virtual float method3(void) = 0;

};

#endif // BASECLASS_H

DerivedClass.h

#ifndef DERIVEDCLASS_H
#define DERIVEDCLASS_H

#include "DerivedClass.h"

class DerivedClass: public BaseClass
{

    public:
        DerivedClass(void);     
};

#endif // DERIVEDCLASS_H

DerivedClass.cpp

#include "DerivedClass.h"

DerivedClass::DerivedClass(void)
{
}

int DerivedClass::method1(void)
{
  // TODO
} 

int DerivedClass::method2(void)
{
  // TODO
}

float DerivedClass::method3(void) 
{
  // TODO
}

尝试编译此代码时,所有虚拟方法都收到以下错误:

When attempting to compile this, I get the following error for all the virtual methods:

no 'int DerivedClass::methodX()' member function declared in class 'DerivedClass'

一旦我在'DerivedClass.h'中声明了这些方法,错误就会消失,因为编译器现在已经知道了这些方法.

As soon as I declare these methods in the 'DerivedClass.h', the errors go away since the compiler is now aware of the methods.

但是,我很困惑.为什么需要在DerivedClass.h中重新声明纯虚函数?当我#include DerivedClass.h时,它将自动包括BaseClass.h,因此我认为我的DerivedClass.cpp应该完全了解这些方法.我做错了什么吗?

However, I'm confused. Why was it necessary to re-declare the pure virtual functions in DerivedClass.h? When I #include DerivedClass.h, that will automatically include BaseClass.h, thus I assume my DerivedClass.cpp should be fully aware of the methods. Am I doing something incorrect?

推荐答案

这种方式无法正常工作.您需要声明要定义的方法,无论它们是否覆盖虚拟方法.

It doesn't work this way. You need to declare the methods you're going to define, whether they're overriding a virtual method or not.

这不仅仅是对语言的不合理要求.没有这个,您将无法定义部分虚拟的类,即,您可能拥有具有method1()通用实现的BaseSubtype,但需要从其派生的类来实现method2()method3()

This isn't just an unreasonable requirement of the language. Without this you would be unable to define partially virtual class, i.e., you could have BaseSubtype that has common implementation of method1() but requires classes derived from it to implement method2() and method3()

这篇关于为什么必须从继承的类中重新声明虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆