C++中的菱形继承问题

什么是菱形继承

1
2
3
4
5
6
7
8
9
10
11
12
class grandfather
{
public:
int age;
grandfather() {
age = 108;
}
};

class father1: public grandfather{};
class father2: public grandfather{};
class son :public father1, public father2{};

这时son就是菱形继承的产物,如果编写以下代码

1
2
3
4
5
6
int main() {
son s;
s.age=4;
cout<<s.age;
return 0;
}

甚至无法通过编译

alt text

如何解决

  1. 手动写明作用域
  2. 使用virtual public 继承
1
2
3
4
5
6
7
8
9
10
11
int main() {
son s;
s.father1::age = 4;
cout << s.father1::age;
return 0;
}

```cpp
class father1:virtual public grandfather{};
class father2:virtual public grandfather{};
class son :public father1, public father2{};

以上两种方式均可以通过编译,但是使用第二种方式的话,p.age, p.father1::age, p.father2::age其实会指向同一块内存区域,既浪费了空间(多了两个vbptr),又没起到任何作用,所以还是要尽量避免菱形继承的使用。


C++中的菱形继承问题
http://example.com/2024/04/08/C-中的菱形继承问题/
作者
Jinming Zhang
发布于
2024年4月8日
许可协议