[英]Please make me understand assigning derived class object to base class pointer- C++
Lets say you have a base class Base and derived class Derived . 假设您有一个基类Base和派生类Derived 。
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
While below code works, 虽然以下代码有效,
Derived *d=new Base(); //no typecasting required here, why?
What's the difference between above two cases? 以上两种情况有什么区别?
Thanks! 谢谢!
Base
is-not-a Derived
, so neither this: Base
不是- Derived
,所以这两个都不是:
Base b;
Derived *d;
d=&b;
nor this: 也不是这样:
Derived* d = new Base();
makes any sense or works. 有意义或可行。 Both would result in something like
两者都会导致类似
error: invalid conversion from 'Base*' to 'Derived*' [-fpermissive]
错误:从“基本*”到“派生*”的无效转换[-fpermissive]
Both are doing exactly the same thing: assigning a Base*
to a Derived*
. 两者都在做完全相同的事情:将
Base*
分配给Derived*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.