考虑这个片段:
#include <iostream>
struct S {
virtual void pure1() = 0;
virtual void pure2() = 0;
};
struct T : S {
void pure1() { std::cout << "T::pure1" << '\n'; }
void pure2() { std::cout << "T::pure2" << '\n'; }
};
void S::pure2() { std::cout << "S::pure2" << '\n';}
int main()
{
T t;
t.S::pure2();
}
它打印S::pure2
。
看看 C++11 标准,我不知道这是怎么发生的。我相信它与 §3.4.5/4 有关:
If the id-expression in a class member access is a qualified-id of the form
class-name-or-namespace-name::...
the class-name-or-namespace-name following the . or -> operator is first looked up in the class of the object expression and the name, if found, is used. Otherwise it is looked up in the context of the entire postfix-expression.
但我不明白如何在基类 S
中使用表达式 t.S::pure2() 找到纯虚函数
同上。pure2()
;
最佳答案
在基类中实现一个纯虚函数是可以的。该标准指定有效(强调我的):
10.4 Abstract classes
2 An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function. [ Note: Such a function might be inherited: see below. —end note ] A virtual function is specified pure by using a pure-specifier (9.2) in the function declaration in the class definition. A pure virtual function need be defined only if called with, or as if with (12.4), the qualified-id syntax (5.1).
如果你没有打电话
t.S::pure2();
然后,省略 S::pure2()
的实现就可以了。如果你没有实现 S::pure2()
但仍然调用了
t.S::pure2();
关于c++ - 标准如何支持在基类 S 中调用纯虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26243781/