【More Effective C++】条款3:不以多态的方式处理数组

 注意:通过array[i]操作本质上是*(array + i),通过父类指针操作子类,会出现未定义的行为


class BST {
public:
    friend std::ostream& operator<<(std::ostream& s, const BST& obj);
private:
    int a;
};
std::ostream& operator<<(std::ostream& s, const BST& obj) {
    s << "haha";
    return s;
}
class BanlanceBST : public BST {
private:
    int b;
};
void printBSTArray(std::ostream& s, const BST array[], int numElements) {
    for (int i = 0; i < numElements; ++i) {
        s << array[i];
    }
}
void deleteBSTArray(std::ostream& s, BST array[]) {
    s << "delete " << static_cast(array) << "\n";
    delete [] array;
}

int main() {
    // BST BSTArray[10];
    // printBSTArray(std::cout, BSTArray, 10);
    // std::cout << "\n";

    // BanlanceBST BanlanceBSTArray[10];
    // printBSTArray(std::cout, BanlanceBSTArray, 10);
    // std::cout << "\n";

    BanlanceBST *balTreeArray = new BanlanceBST[10];
    deleteBSTArray(std::cout, balTreeArray);

    BST *bta = new BST[10];
    deleteBSTArray(std::cout, bta);

    return 0;
}

你可能感兴趣的:(More,Effective,C++,c++,算法,开发语言)