gpt4 book ai didi

c++ - 如何在实现文件中实现虚方法?

转载 作者:IT老高 更新时间:2023-10-28 22:26:30 26 4
gpt4 key购买 nike

C++ 菜鸟问题:

假设我想使用具有多种方法的抽象类作为接口(interface):

// this is AbstractBase.hpp

class AbstractBase
{
public:
virtual int foo() = 0;
virtual int bar() = 0;
// imagine several more pure virtual methods are here
};

我想要一个实现所有虚方法的子类,我不想在头文件中实现它们,而是在它们的实现文件中实现。

我真的必须像这样在子类声明中再次声明所有这些方法吗?我在想应该有一种方法可以避免这一步(来自 ObjC、Java)

// this is Concrete.hpp

class Concrete : public AbstractBase
{
public:
int foo();
int bar();
// need to copy paste all the method declarations here again...? why?
};

我想做的是像这样实现实现文件中的方法:

// this is Concrete.cpp

#include "Concrete.hpp"

int Concrete::foo()
{
return 666;
}

// etc...

但无法弄清楚如何,除非在每个子类中重新声明接口(interface)。

最佳答案

虽然如果将定义与“Java-style”声明结合起来,可以避免第二次编写函数头签名,即

class Concrete : public AbstractBase
{
public:
int foo() override {return 666;}
};

当您想单独提供定义时,C++ 不允许您避免 声明 步骤。

这样做的原因是声明是主要的,而定义是次要的。为了能写

int Concrete::foo()
{
return 666;
}

在您的 CPP 文件中,您需要告诉编译器 Concrete 有意覆盖其 header 中的 foo

关于c++ - 如何在实现文件中实现虚方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com