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。
你的第二个文本块只是更多的声明:
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)
| 归档时间: |
|
| 查看次数: |
2414 次 |
| 最近记录: |