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

为什么下面的代码会产生这个错误,即使 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();
}
32697 次浏览

You need:

class d : public c

class inheritance is private by default.

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