int firstNumber, secondNumber;
...
double result = ((double)firstNumber)/secondNumber;
//如果用上述新的类型转换方法,你应该这样写:
double result = static_cast<double>(firstNumber)/secondNumber;
数组中难免会遇到数组索引运算符array[ i ],本质上式一个指针算术表达式*(array+i),通过数组原类型的大小计算每个数组元素的地址。如果将派生类对象数组实参传递给原本为基类对象数组的形参(类似多态的方式),那么代码将仍以基类对象占用的内存大小计算对象数组的每个元素地址 ,问题的关键在于派生类对象几乎总是比基类对象要大,这样计算出来的元素地址就会有问题,行为是未定义的。
cpp复制代码
class BST { ... };
class BalancedBST: public BST { ... };
void printBSTArray(ostream& s,
const BST array[],
int numElements)
{
for (int i = 0; i < numElements; ) {
s << array[i]; //假设BST类
} //重载了操作符<<
}
BalancedBST bBSTArray[10];
...
printBSTArray(cout, bBSTArray, 10); //报错
typedef EquipmentPiece* PEP; // PEP 指针指向
//一个EquipmentPiece对象
PEP bestPieces[10]; // 正确, 没有调用构造函数
PEP *bestPieces = new PEP[10]; // 也正确
//在指针数组里的每一个指针被重新赋值,以指向一个不同的EquipmentPiece对象:
for (int i = 0; i < 10; ++i)
bestPieces[i] = new EquipmentPiece( ID Number );
// 为大小为10的数组 分配足够的内存
// EquipmentPiece 对象;
// operator new[] 函数
void *rawMemory =
operator new[](10*sizeof(EquipmentPiece));
// make bestPieces point to it so it can be treated as an
// EquipmentPiece array
EquipmentPiece *bestPieces =
static_cast<EquipmentPiece*>(rawMemory);
// construct the EquipmentPiece objects in the memory
// 使用"placement new" (参见条款8)
for (int i = 0; i < 10; ++i)
new (&bestPieces[i]) EquipmentPiece( ID Number );
cpp复制代码
// 以与构造bestPieces对象相反的顺序
// 解构它。
- List item
for (int i = 9; i >= 0; --i)
bestPieces[i].~EquipmentPiece();
// deallocate the raw memory
operator delete[](rawMemory);
//如果你忘记了这个要求而使用了普通的数组删除方法,那么你程序的运行将是不可预测的。这是因为:直接删除一个不是用new操作符来分配的内存指针,其结果没有被定义。
delete [] bestPieces; // 没有定义! bestPieces
//不是用new操作符分配的。