Item 3: Never treat arrays polymorphically.

  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?
结果不可预测。
避免从具体类派生具体类。基类最好是抽象类。
抽象类不能定义对象!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值