为什么对基类的赋值有效,但是对派生类的赋值是编译错误? [英] Why is an assignment to a base class valid, but an assignment to a derived class a compilation error?

查看:91
本文介绍了为什么对基类的赋值有效,但是对派生类的赋值是编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题。请考虑以下内容:

This was an interview question. Consider the following:

struct A {}; 
struct B : A {}; 
A a; 
B b; 
a = b;
b = a; 

为什么 b = a; 错误,而 a = b; 是否完全正常?

Why does b = a; throw an error, while a = b; is perfectly fine?

推荐答案

因为 B 的隐式声明的复制赋值操作符隐藏了隐式 A 的声明复制赋值运算符。

Because the implicitly declared copy assignment operator of B hides the implicitly declared copy assignment operator of A.

所以对于 b = a ,只有 operator = of B 是候选人。但是它的参数具有类型 B const& ,它不能由 A 参数初始化(你需要一个向下转换) 。所以你得到一个错误。

So for the line b = a, only the the operator= of B is a candidate. But its parameter has type B const&, which cannot be initialized by an A argument (you would need a downcast). So you get an error.

这篇关于为什么对基类的赋值有效,但是对派生类的赋值是编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆