more effective c++非尾端类设计抽象类(41)

先看代码:++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Animal {
public:
int a;
public:
Animal& operator=(const Animal& rhs) {
this->a = rhs.a;
return *this;
}
};
class Lizard : public Animal {
public:
int d;
public:
Lizard& operator=(const Lizard& rhs) {
this->d = rhs.d;
return *this;
}
};
class Chicken : public Animal {
public:
string str;
public:
Chicken& operator=(const Chicken& rhs) {
this->str = rhs.str;
return *this;
}
};
Lizard liz1;
Lizard liz2;
Animal* panimal1 = &liz1;
Animal* panimal2 = &liz2;
*panimal1 = *panimal2;
//问题1:执行最后一个函数时,必定会执行Animal的赋值函数。 导致情况:liz1的Animal部分被修改,
liz1的Animal内容变得和liz2的Animal内容一样。
//采取行动:虚化赋值函数(注意:成员函数是基类)
virtual Animal& operator=(const Animal& rhs);
virtual Lizard& operator=(const Animal& rhs);
virtual Chicken& operator=(const Animal& rhs);
//问题:虽然它现在会动态改变赋值对象函数了,但存在”异型赋值“(类没有的成员进行赋值)
//采取行动:重载函数,动态强制转换
例如Lizard:
Lizard& operator=(const Animal& rhs);//用来转换本地的
virtual Lizard& operator=(const Animal& rhs);//用来转换继承关系的
{
return operator=(dynamic_cast<const Lizard&>(rhs));
//当被转换的类型不是Lizard的时候,就会抛出异常错误。
}

后面的纯虚化基类,我看不太懂;

// //