2

有人可以向我解释最后 5 行,为什么当 Manager 是 Employee 的子对象时会发生这种情况?

ostream& operator << (
   ostream &, const Employee &
);
Employee  e;
Manager   m;
Employee &eRef1 = e;  // OK!     
Employee &eRef2 = m;  // OK!  
Manager  &mRef1 = e;  // Compile error!
Manager  &mRef2 = m;  // OK!
cout << e << m;       // OK! 
4

3 回答 3

5

这正是因为您所说的:Manager派生自Employee(我想这就是您说"Manager是 " 的子对象时的Employee意思)。这意味着 的所有实例Manager也是 的实例Employee,但反之则不然。

在这里,您试图将对 a 的引用绑定到Managertype 的对象Employee。但是由于一个实例Employee不是一个实例Manager(反之亦然!)你会得到一个错误。

如果您想了解为什么这是正确的,请尝试考虑如果您没有收到错误会发生什么

Employee e;
// ...
Manager& m = e; // This won't work, but let's suppose it did...
int s = m.get_size_of_managed_team(); // Huh?

如果您可以将对 a 的引用绑定到一个实际上不是aManager的对象,您可以为它调用实际对象不支持的函数。这将是混乱。因此,编译器根本不会出现这种情况。Manager

于 2013-02-20T17:03:18.160 回答
3

引用表现出多态行为。也就是说,您可以引用使用派生类初始化的基类。但是,您不能引用使用基类初始化的派生类。

由于Employee是 的基础Manager,因此您无法Manager使用员工初始化引用。其余的初始化都很好。

Reference | Initialised with | Valid?
----------|------------------|--------
Base&     | Base             | Yes
Base&     | Derived          | Yes
Derived&  | Base             | No
Derived&  | Derived          | Yes

这是直观的。为什么你会允许任何Employee人伪装成 a Manager?想象一下在这样的地方工作 - 会很混乱!

于 2013-02-20T17:03:05.207 回答
1

在这样的层次结构中,类基于其他类,这样想。

A -> B -> C -> D

在该示例中,let -> 表示 B 继承自 A 等。

如果你这样想,类可以变成比它们少的类(向左):D 可以变成 C、B 或 A。对于 B,右侧的类是不可访问的,因为它们“更高” “在链条上,因此你不能把 B 变成 C 或 D。

在你的例子中,

员工 -> 经理

Managers can move left to Employee, so you can morph it that way, but Manager is to the RIGHT of Employee, which as said earlier, makes that transition impossible.

The reasoning is because, when you inherit, you gain all the benefits of the base class; variables, functions, all of it. When you try to go up the chain, you're adding variables, classes, etc, and you essentially have to re-create your object to do so, as it now takes more memory and will behave differently than originally. But, going down the tree, you're essentially just stripping an onion; taking off layers to reveal the spot of the onion you're after. They're all there to begin with, they're just not directly visible since they make up the smaller parts.

于 2013-02-20T17:13:34.337 回答