We know that array is a pointer to the beginning of the array, but how far away from the memory location pointed to by array is the memory location pointed to by array+i?
我们知道array是一个指向数组起始地址的指针,但是array中各元素内存地址与数组的起始地址的间隔究竟有多大呢?
The problem pops up in a different guise if you try to delete an array of derived class objects through a base class pointer. Here's one way you might innocently attempt to do it.
如果你试图删除一个含有派生类对象的数组,将会发生各种各样的问题。以下是一种你可能的不正确的做法。
Just as this kind of loop failed to work when you wrote it, it will fail to work when your compilers write it, too.
因为你所编写的循环语句根本不能正运行,所以当编译成可执行代码后,也不可能正常运行。
Item 3: Never treat arrays polymorphically.
class BST { ... };
class BalancedBST: public BST { ... };
void printBSTArray(ostream& s,
const BST array[],
int numElements)
{
for (int i = 0; i < numElements; ++i) {
s << array[i]; // this assumes an
} // operator<< is defined
} // for BST objects
BST BSTArray[10];
...
printBSTArray(cout, BSTArray, 10); // works fine
BalancedBST bBSTArray[10];
...
printBSTArray(cout, bBSTArray, 10); // works fine?
结果不可预测。
避免从具体类派生具体类。基类最好是抽象类。
抽象类不能定义对象!!