请考虑以下代码段:
#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.
但我不明白纯子函数pure2()是如何在基类S中找到的,表达式为t.S :: 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();