//Item M3:不要對數組使用多態
#include<iostream>
using namespace std;
class BST {
public:
BST(){}
BST(int data):data(data) {
}
int data;
friend ostream& operator<<(ostream& os, const BST rhs);
};
ostream& operator<<(ostream& os, const BST rhs) {
return os << rhs.data << " ";
}
class BalanceBST:public BST{
public:
BalanceBST(){}
BalanceBST(int data, int other) :BST(data), other(other) {
}
int other;
};
void printBSTArray(ostream&s, const BST array[], int numElements) {
for (int i = 0; i < numElements; i++) {
s << array[i];
}
cout << endl;
}
void deleteArray(ostream& logStream, BST array[]){
logStream << "Deleting array at address "
<< static_cast<void*>(array) << '\n';
delete[] array;
}
int main() {
BST bst[5] = { 11,22,33,44,55 };
BalanceBST bst1[5] = { {11,0},{22,0},{33,0},{44,0},{55,0} };
printBSTArray(cout, bst, 5);
printBSTArray(cout, bst1, 5);//無警告地編譯這個函數 結果 11 0 22 0 33
//* array[I]只是一個指針算法的縮寫:它所代表的是*(array)。我們知道array是一個指向數組起始地址的指針,但是array中各元素內存地址與數組的起始地址的間隔究竟有多大呢?它們的間隔是i*sizeof(一個在數組裏的對象)因爲在array數組[0]到[I]間有I個對象。編譯器爲了建立正確遍歷數組的執行代碼,它必須能夠確定數組中對象的大小,這對編譯器來說是很容易做到的。參數array被聲明爲BST類型,所以array數組中每一個元素都是BST類型,因此每個元素與數組起始地址的間隔是i*sizeof(BST)*/
BalanceBST *balTreeArray = new BalanceBST[50];// 建立一個BalancedBST對象數
// ...
deleteArray(cout, balTreeArray); // 記錄這個刪除操作這裏面也掩藏着你看不到的指針算法。語言規範中說通過一個基類指針來刪除一個含有派生類對象的數組,結果將是不確定的。
//多態和指針算法不能混合在一起來用,所以數組與多態也不能用在一起。
system("pause");
return 0;
}
M3:不要對數組使用多態
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.