⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 m.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
📖 第 1 页 / 共 5 页
字号:
Remember that this approximation is not performing a true dynamic_cast; there is no way to tell if the cast fails.I know, I know, the new casts are ugly and hard to type. If you find them too unpleasant to look at, take solace in the knowledge that C-style casts continue to be valid. However, what the new casts lack in beauty they make up for in precision of meaning and easy recognizability. Programs that use the new casts are easier to parse (both for humans and for tools), and they allow compilers to diagnose casting errors that would otherwise go undetected. These are powerful arguments for abandoning C-style casts, and there may also be a third: perhaps making casts ugly and hard to type is a good thing. Back to Item 2: Prefer C++-style castsContinue to Item 4: Avoid gratuitous default constructorsItem 3: Never treat arrays polymorphically.One of the most important features of inheritance is that you can manipulate derived class objects through pointers and references to base class objects. Such pointers and references are said to behave polymorphically as if they had multiple types. C++ also allows you to manipulate arrays of derived class objects through base class pointers and references. This is no feature at all, because it almost never works the way you want it to.For example, suppose you have a class BST (for binary search tree objects) and a second class, BalancedBST, that inherits from BST: class BST { ... };class BalancedBST: public BST { ... };In a real program such classes would be templates, but that's unimportant here, and adding all the template syntax just makes things harder to read. For this discussion, we'll assume BST and BalancedBST objects contain only ints.Consider a function to print out the contents of each BST in an array of BSTs: 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 objectsThis will work fine when you pass it an array of BST objects: BST BSTArray[10];...printBSTArray(cout, BSTArray, 10);          // works fineConsider, however, what happens when you pass printBSTArray an array of BalancedBST objects: BalancedBST bBSTArray[10];...printBSTArray(cout, bBSTArray, 10);         // works fine?Your compilers will accept this function call without complaint, but look again at the loop for which they must generate code: for (int i = 0; i < numElements; ++i) {  s << array[i];}Now, array[i] is really just shorthand for an expression involving pointer arithmetic: it stands for *(array+i). 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? The distance between them is i*sizeof(an object in the array), because there are i objects between array[0] and array[i]. In order for compilers to emit code that walks through the array correctly, they must be able to determine the size of the objects in the array. This is easy for them to do. The parameter array is declared to be of type array-of-BST, so each element of the array must be a BST, and the distance between array and array+i must be i*sizeof(BST).At least that's how your compilers look at it. But if you've passed an array of BalancedBST objects to printBSTArray, your compilers are probably wrong. In that case, they'd assume each object in the array is the size of a BST, but each object would actually be the size of a BalancedBST. Derived classes usually have more data members than their base classes, so derived class objects are usually larger than base class objects. We thus expect a BalancedBST object to be larger than a BST object. If it is, the pointer arithmetic generated for printBSTArray will be wrong for arrays of BalancedBST objects, and there's no telling what will happen when printBSTArray is invoked on a BalancedBST array. Whatever does happen, it's a good bet it won't be pleasant.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: // delete an array, but first log a message about its// deletionvoid deleteArray(ostream& logStream, BST array[]){  logStream << "Deleting array at address "            << static_cast<void*>(array) << '\n';delete [] array;}BalancedBST *balTreeArray =                  // create a BalancedBST  new BalancedBST[50];                       // array...deleteArray(cout, balTreeArray);             // log its deletionYou can't see it, but there's pointer arithmetic going on here, too. When an array is deleted, a destructor for each element of the array must be called (see Item 8). When compilers see the statement delete [] array;they must generate code that does something like this: // destruct the objects in *array in the inverse order// in which they were constructedfor (        int i = the number of elements in the array - 1;        i >= 0;        --i)  {    array[i].BST::~BST();                     // call array[i]'s  }                                           // destructorJust as this kind of loop failed to work when you wrote it, it will fail to work when your compilers write it, too. The language specification says the result of deleting an array of derived class objects through a base class pointer is undefined, but we know what that really means: executing the code is almost certain to lead to grief. Polymorphism and pointer arithmetic simply don't mix. Array operations almost always involve pointer arithmetic, so arrays and polymorphism don't mix.Note that you're unlikely to make the mistake of treating an array polymorphically if you avoid having a concrete class (like BalancedBST) inherit from another concrete class (such as BST). As Item 33 explains, designing your software so that concrete classes never inherit from one another has many benefits. I encourage you to turn to Item 33 and read all about them. Back to Item 3: Never treat arrays polymorphicallyContinue to OperatorsItem 4: Avoid gratuitous default constructors.A default constructor (i.e., a constructor that can be called with no arguments) is the C++ way of saying you can get something for nothing. Constructors initialize objects, so default constructors initialize objects without any information from the place where the object is being created. Sometimes this makes perfect sense. Objects that act like numbers, for example, may reasonably be initialized to zero or to undefined values. Objects that act like pointers ( Item 28) may reasonably be initialized to null or to undefined values. Data structures like linked lists, hash tables, maps, and the like may reasonably be initialized to empty containers.Not all objects fall into this category. For many objects, there is no reasonable way to perform a complete initialization in the absence of outside information. For example, an object representing an entry in an address book makes no sense unless the name of the thing being entered is provided. In some companies, all equipment must be tagged with a corporate ID number, and creating an object to model a piece of equipment in such companies is nonsensical unless the appropriate ID number is provided.In a perfect world, classes in which objects could reasonably be created from nothing would contain default constructors and classes in which information was required for object construction would not. Alas, ours is not the best of all possible worlds, so we must take additional concerns into account. In particular, if a class lacks a default constructor, there are restrictions on how you can use that class.Consider a class for company equipment in which the corporate ID number of the equipment is a mandatory constructor argument: class EquipmentPiece {public:  EquipmentPiece(int IDNumber);  ...};Because EquipmentPiece lacks a default constructor, its use may be problematic in three contexts. The first is the creation of arrays. There is, in general, no way to specify constructor arguments for objects in arrays, so it is not usually possible to create arrays of EquipmentPiece objects: EquipmentPiece bestPieces[10];           // error! No way to call                                         // EquipmentPiece ctors  EquipmentPiece *bestPieces =  new EquipmentPiece[10];                // error! same problemThere are three ways to get around this restriction. A solution for non-heap arrays is to provide the necessary arguments at the point where the array is defined: int ID1, ID2, ID3, ..., ID10;            // variables to hold                                         // equipment ID numbers...EquipmentPiece bestPieces[] = {          // fine, ctor arguments  EquipmentPiece(ID1),                   // are provided  EquipmentPiece(ID2),  EquipmentPiece(ID3),  ...,  EquipmentPiece(ID10)};Unfortunately, there is no way to extend this strategy to heap arrays.A more general approach is to use an array of pointers instead of an array of objects: typedef EquipmentPiece* PEP;             // a PEP is a pointer to                                         // an EquipmentPiecePEP bestPieces[10];                      // fine, no ctors calledPEP *bestPieces = new PEP[10];           // also fine

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -