c++ - 标准如何支持在基类 S 中调用纯虚函数?

标签 c++ c++11 lookup language-lawyer

考虑这个片段:

#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/

相关文章:

excel - 索引匹配与间接和部分匹配?

c++ - 模板函数参数显式类型声明

c++ - 无法将 std::bind 的结果转换为 std::function

c++ - 为什么 std::pair<A,B> 与 std::tuple<A,B> 不同? (真的没有办法吗?)

excel - 解释LOOKUP公式

List.assoc 的 OCaml 复杂性

c++ - 使用 CXX 社区插件在 Sonarqube-5.6.6(LTS) 中导入 Gcov 报告

c++ - MPI_Bcast 错误

c++ - 网络回复后Qt更新

c++ - 是否有调试机制、变通方法、包装器或工具来检测 shared_ptr 循环?