C++ : 成员的行外声明必须是纯虚函数的定义错误

Naq*_*q Z 2 c++ virtual-functions pure-virtual

在我的头文件中,我已经声明了 2 个公共成员文件是像这样的纯虚函数

头文件

class Whatever
{
public:
    virtual bool Update() = 0;
    virtual bool ShouldBeVisible() = 0;
};
Run Code Online (Sandbox Code Playgroud)

执行

bool Whatever::Update();

bool Whatever::ShouldBeVisible();
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编译,我把一个错误,指出:乱行成员的声明必须在一个定义更新ShouldBeVisible。当我在实现中去掉分号时,我得到一个不同的错误,上面写着“预期的”“;” 之后顶层声明符成员外的网上申报必须是定义用于更新之后函数声明预期的函数体ShouldBeVisible

Sqe*_*aky 5

你的第二个文本块只是更多的声明:

bool Whatever::Update();
Run Code Online (Sandbox Code Playgroud)

要定义,必须有一些实现:

bool Whatever::Update()
{
    return true; // or any other code
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我看到你想让它们成为纯虚函数,这意味着没有定义。纯虚函数就像要求另一个类的承诺来实现/定义这些函数。您应该= 0按原样使用,除非在另一个类中,否则不要再次定义它们。

然后你可以编写实现你的任何接口的类。稍后这将让您使用您的Whatevers 而无需特别知道您拥有哪种类型。

class IsAWhatever : public Whatever
{
public:
    virtual bool Update() override;
    virtual bool ShouldBeVisible() override;
};


bool IsAWhatever::Update()
{
    return true; // or any other code
}
Run Code Online (Sandbox Code Playgroud)

使用示例:

int someFuncThatUsesWhatever(const Whatever& wut); // Defined elsewhere

int main()
{
    IsAWhatever lolwut;

    // This functions accepts a reference to any Whatever so it can
    // take our IsAWhatever class. This is "Runtime Polymorphism" if
    // you want to google it. It is useful for making writing code
    // that might become old and letting it call new code. 
    return someFuncThatUsesWhatever(lolwut);
}
Run Code Online (Sandbox Code Playgroud)

  • IIRC 提供纯虚函数的实现是合法的。派生类仍然需要提供它们的实现,但这些实现可能会调用纯实现。(我真的不喜欢这样做的代码..但它是合法的) (3认同)
  • @Sqeaky 有一个例外,定义*必须*存在:如果纯虚方法是析构函数,尽管无论如何这都是一种特殊情况。但我想你是对的,这是代码味道。 (2认同)