这是一个解释纯函数概念的示例
#include <iostream>
struct A
{
virtual ~A() = default;
virtual void what() const = 0;
};
void A::what() const
{
std::cout << "struct A";
}
struct B : A
{
virtual void what() const = 0;
};
void B::what() const
{
A::what();
std::cout << ", struct B : A";
}
struct C : B
{
void what() const;
};
void C::what() const
{
B::what();
std::cout << ", struct C: B";
}
int main()
{
// A a; compiler error
// B b; compiler error
C c;
const A &rc = c;
rc.what();
std::cout << std::endl;
return 0;
}
程序输出为
struct A, struct B : A, struct C: B
在此示例中,类 A 和 B 是抽象类,因为它们具有纯虚函数,尽管它们中的每一个都提供了其纯虚函数的相应定义。
而且只有类 C 不是抽象的,因为它将虚函数重新声明为非纯虚函数。