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
conversion from derived * to base * exists but is inaccessible
提问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 = ⅆ
cc->fun();
}
回答by Luchian Grigore
You need:
你需要:
class d : public c
class
inheritance is private
by default.
class
继承是private
默认的。
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.
当您从 aclass
或 a私下继承时struct
,您明确表示,从派生类型到基类型的直接转换是不可能的。