gpt4 book ai didi

c++ - 在类定义之外定义纯虚函数

转载 作者:行者123 更新时间:2023-11-28 06:20:08 24 4
gpt4 key购买 nike

显然,内联定义是不允许的。

所以,我想知道这种使用二进制范围解析运算符在类定义之外定义纯虚函数的做法在哪些情况下有用

One scenario I can think of is suppose all the derived classes have some common code/functionality in the pure virtual function definition and that common functionality can be included in the base class definition of the pure virtual function itself and the base class version of the pure virtual function can be called inside the derived classes' definition of the pure virtual function. (Not sure if the syntax works though).

最佳答案

确实,当您想要调用基类的纯虚成员函数中定义的通用功能时。

(Not sure if the syntax works though).

它是这样工作的:

#include <iostream>
#include <memory>

struct Foo
{
virtual void f() = 0;
virtual ~Foo() = default;
};

void Foo::f()
{
std::cout << "common functionality" << std::endl;
}

struct Bar: Foo
{
void f() override
{
Foo::f(); // call the base pure virtual implementation, common functionality
std::cout << "derived functionality" << std::endl;
}
};

int main()
{
std::unique_ptr<Foo> upFoo{std::make_unique<Bar>()};
upFoo->f();
}

另请参阅 Scott Meyers 的 Effective C++ 的第 34 项,以获取有关该主题的非常详细的讨论。

关于c++ - 在类定义之外定义纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449492/

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