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

c – 公共接口方法的私有实现

发布时间:2020-12-16 07:15:18 所属栏目:百科 来源:网络整理
导读:参见英文答案 Overriding public virtual functions with private functions in C++????????????????????????????????????7个 我遇到了一段代码,方法是通过公共接口公开,而实现是私有的.我不确定预期的行为应该是什么.简化示例: #include iostreamclass Int
参见英文答案 > Overriding public virtual functions with private functions in C++????????????????????????????????????7个
我遇到了一段代码,方法是通过公共接口公开,而实现是私有的.我不确定预期的行为应该是什么.简化示例:

#include <iostream>

class Interface
{
public:
    virtual ~Interface() {}
    virtual void myIfMethod() = 0;
};

class Derived : public Interface
{
private:
    void myIfMethod(){std::cout << "private method invoked via public interface" << std::endl;}
};

int main()
{
    Interface* myObj = new Derived;
    myObj->myIfMethod();
    delete myObj;
    return 0;
}

此示例编译并执行时没有警告:http://ideone.com/1Ouwk4

这是一个正确且明确定义的行为吗?如果是这样,为什么?

注意,问题不在于公共实现的私有接口方法(SO上有多个这样的问题),反之亦然.

解决方法

C标准草案

访问虚拟功能[class.access.virt]

1 The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by
the rules for a function that later overrides it.

2 Access is checked at the call point using the type of the expression used to denote the object for which the member function is called (B* in the example above). The access of the member function in the class in which it was defined (D in the example above) is in general not known.

该函数通过类型为Interface的指针调用,其中成员函数是公共的,因此允许访问.派生成员函数的访问是未知的,并且没有任何效果.就标准而言,行为是正确的并且定义良好.

当然,将覆盖函数定义为私有可能是毫无意义的,因为无论如何它都可以通过虚拟调度访问.

(编辑:李大同)

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

    推荐文章
      热点阅读