加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 标准如何在基类S中支持纯虚函数的这种调用?

发布时间:2020-12-16 09:54:37 所属栏目:百科 来源:网络整理
导读:请考虑以下代码段: #include iostreamstruct 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::pur
请考虑以下代码段:

#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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读