C++ 多重继承不明确

标签 c++

我在 C++ 多重继承方面遇到问题。这是我的代码,当我调用 display() 函数时,它给我的成员“display”请求不明确。但是M类的display()函数是私有(private)的。

#include<iostream>
#include<conio.h>
#include<stdio.h>

using namespace std;
class M
{

    void display()
    {
        cout<<"Class M"<<endl;
    }
};

class N
{
    public:
        void display()
        {
            cout<<"Class N"<<endl;
        }
};

class P:public M,public N
{

};

int main()
{

    P *ob = new P();
    ob->display();    // Why its giving me ambiguity error? Since only one copy is there right!!
    getch();
    return 0;
}

谁能告诉我这个问题到底是为什么吗?

最佳答案

正如许多人已经提到的,重载解析不包括可见性(publicprivateprotected)。假设您只希望公共(public)版本在 P 中可见,则应在 P 的公共(public)接口(interface)中使用 using 声明:

class P: public M, public N
{
public:
    using N::display;
};

恕我直言,这比必须在每次调用中提供范围(obj->N::display())要优雅得多。

关于C++ 多重继承不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31696067/

相关文章:

c++ - 模板继承 C++

c++ - 高效获取 C++ 链表中最大的 3 个整数(未排序)

c++ - 在其构造函数中将对象的指针传递给另一个类

c++ - Qt C++初始化一个QStringList类成员

c++ - Xcode 10.3 构建失败 “Undefined symbols for architecture x86_64”

c++ - 如何从链表中删除这些节点?

c++ - 使用模板化函数减少代码

c++ - SQLite - 编码问题

python - 取得引用的 Eigen3 矩阵的所有权

C++ 传递函数的问题(数学不加起来)