C++ 从派生 * 到基 * 的转换存在但不可访问

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10472848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:06:44  来源:igfitidea点击:

conversion from derived * to base * exists but is inaccessible

c++inheritance

提问by user1232138

Why does the follwing code produce this error even though c is a struct and has a public inheritance by default??

为什么即使 c 是一个结构并且默认情况下具有公共继承,以下代码也会产生此错误?

struct c 
{
protected:
    int i;
public:
    c(int ii=0):i(ii){}
    virtual c *fun();
};

c* c::fun(){
    cout<<"in c";
    return &c();
}

class d : c
{
 public:
    d(){}
    d* fun()
    {
        i = 9;
        cout<<"in d"<<'\t'<<i;
        return &d();
    }
};


int main()
{
    c *cc;
    d dd;
    cc = &dd;
    cc->fun();
}

回答by Luchian Grigore

You need:

你需要:

class d : public c

classinheritance is privateby default.

class继承是private默认的。

When you privately inherit from a classor a struct, you explicitly say, among other things, that direct conversion from a derived type to a base type isn't possible.

当您从 aclass或 a私下继承时struct,您明确表示,从派生类型到基类型的直接转换是不可能的。