假设你有一个基类基础和派生类派生。
Base b;
Derived *d;
d=&b; // this line gives error, why? I think it asks for typecasting, why?
//When you assign derived class object address to base class pointer, it works fine. Why not the above case works fine
虽然以下代码有效,
Derived *d=new Base(); //no typecasting required here, why?
上述两种情况有什么区别?
谢谢!
答案 0 :(得分:6)
Base
is-not-a Derived
,所以这两个都没有:
Base b;
Derived *d;
d=&b;
也不是:
Derived* d = new Base();
有任何意义或作品。两者都会产生类似
的结果错误:从“Base *”到“Derived *”[-fpermissive]
的无效转换
两者都做了完全相同的事情:将Base*
分配给Derived*
。