我不知道为什么下面的代码可以编译和运行(工作正常)。
#include <iostream>
struct Base
{
virtual std::ostream& display(std::ostream& os) const = 0;
friend std::ostream& operator<<(std::ostream& lhs, const Base& rhs)
{
return rhs.display(lhs);
}
};
struct A: Base
{
virtual std::ostream& display(std::ostream& os) const
{
return os << "A" << std::endl;
}
};
struct B: A
{
virtual std::ostream& display(std::ostream& os) const
{
return os << "B" << std::endl;
}
};
int main()
{
A a;
std::cout << a << std::endl;
B b;
std::cout << b << std::endl;
}
我在类中定义了operator<<
唯一的一次Base
,它调用了纯virtual display
函数。此方案通常用于避免operator<<
在派生类中进行重写,即在基类中仅对其定义一次,然后将虚拟分派与另一个函数一起使用(在我的情况下为display()
)。
您能解释一下为什么我能够Base
在实现中在类内部调用纯虚函数friend std::ostream& operator<<(...)
吗?我认为这不可能。
您可以调用纯虚函数,因为到调用它时该函数不再是纯虚函数:派生类必须重写它才能停止“抽象”。
编译器知道您不能单独实例化类Base
。这意味着您将无法调用operator <<
没有为纯虚函数提供适当替代的任何类。这就是编译器允许您进行调用的原因:它知道在运行时将有一个实现。
注意:调用纯虚函数的唯一方法是从基类的构造函数中调用它。由于该函数是纯虚函数,因此会导致未定义的行为。现代编译器会警告您有关此问题的信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句