Effective C++ 避免数组多态

 1 #include <iostream>
 2 #include <cstdlib>
 3 
 4 using namespace std;
 5 
 6 class Base {
 7     public:
 8         int idx;
 9         Base(int _idx=0) : idx(_idx) {}
10         
11         void show() {cout<<"Base"<<idx<<endl;}
12         void print() {cout<<idx<<endl;}
13 };
14 
15 class Derive : public Base {
16     public:
17         int time[20];
18         Derive(int _idx = 0) : Base(_idx) {}
19         void show() {cout<<"Derive"<<endl;}
20 };
21 
22 void traversal(Base a[], int n) {
23     for (int i=0; i < n; i++) {
24         a[i].show();
25     }
26 }
27 
28 void deleteArray(Base a[]) {
29     delete[] a;
30 }
31 
32 int main() {
33     Derive d[10];
34     traversal(d, 10);
35     
36     deleteArray(d);
37     
38     system("pause");
39     return 0;
40 }

 delete[] a 将发生错误,因为编译器根据Base类型的大小来计算数组a中的各个元素的偏移地址再调用其析构函数,但是传入的实际上是Derive类型因而当程序运行时并不能得到元素正确的偏移,从而程序崩溃。

这个不说以前还真没这么想过

原文地址:https://www.cnblogs.com/lailailai/p/3657532.html