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

📄 ec3.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
📖 第 1 页 / 共 4 页
字号:
This class has a pure virtual function, so it's abstract, and it has a virtual destructor, so you can rest assured that you won't have to worry about the destructor problem. There is one twist, however: you must provide a definition for the pure virtual destructor: AWOV::~AWOV() {}           // definition of pure                           // virtual destructorYou need this definition, because the way virtual destructors work is that the most derived class's destructor is called first, then the destructor of each base class is called. That means that compilers will generate a call to ~AWOV even though the class is abstract, so you have to be sure to provide a body for the function. If you don't, the linker will complain about a missing symbol, and you'll have to go back and add one.You can do anything you like in that function, but, as in the example above, it's not uncommon to have nothing to do. If that is the case, you'll probably be tempted to avoid paying the overhead cost of a call to an empty function by declaring your destructor inline. That's a perfectly sensible strategy, but there's a twist you should know about.Because your destructor is virtual, its address must be entered into the class's vtbl (see Item M24). But inline functions aren't supposed to exist as freestanding functions (that's what inline means, right?), so special measures must be taken to get addresses for them. Item 33 tells the full story, but the bottom line is this: if you declare a virtual destructor inline, you're likely to avoid function call overhead when it's invoked, but your compiler will still have to generate an out-of-line copy of the function somewhere, too. Back to Item 14: Make sure base classes have virtual destructors.Continue to Item 16: Assign to all data members in operator=.Item 15: Have operator= return a reference to *this.Bjarne Stroustrup, the designer of C++, went to a lot of trouble to ensure that user-defined types would mimic the built-in types as closely as possible. That's why you can overload operators, write type conversion functions (see Item M5), take control of assignment and copy construction, etc. After so much effort on his part, the least you can do is keep the ball rolling.Which brings us to assignment. With the built-in types, you can chain assignments together, like so: int w, x, y, z;w = x = y = z = 0;As a result, you should be able to chain together assignments for user-defined types, too: string w, x, y, z;               // string is "user-defined"                                 // by the standard C++                                 // library (see Item 49)w = x = y = z = "Hello";As fate would have it, the assignment operator is right-associative, so the assignment chain is parsed like this: w = (x = (y = (z = "Hello")));It's worthwhile to write this in its completely equivalent functional form. Unless you're a closet LISP programmer, this example should make you grateful for the ability to define infix operators:w.operator=(x.operator=(y.operator=(z.operator=("Hello"))));This form is illustrative because it emphasizes that the argument to w.operator=, x.operator=, and y.operator= is the return value of a previous call to operator=. As a result, the return type of operator= must be acceptable as an input to the function itself. For the default version of operator= in a class C, the signature of the function is as follows (see Item 45): C& C::operator=(const C&);You'll almost always want to follow this convention of having operator= both take and return a reference to a class object, although at times you may overload operator= so that it takes different argument types. For example, the standard string type provides two different versions of the assignment operator: string&                            // assign a stringoperator=(const string& rhs);      // to a stringstring&                            // assign a char*operator=(const char *rhs);        // to a stringNotice, however, that even in the presence of overloading, the return type is a reference to an object of the class.A common error amongst new C++ programmers is to have operator= return void, a decision that seems reasonable until you realize it prevents chains of assignment. So don't do it.Another common error is to have operator= return a reference to a const object, like this: class Widget {public:  ...                                            // note  const Widget& operator=(const Widget& rhs);    // const  ...                                            // return};                                               // typeThe usual motivation is to prevent clients from doing silly things like this: Widget w1, w2, w3;...(w1 = w2) = w3;         // assign w2 to w1, then w3 to                        // the result! (Giving Widget's                        // operator= a const return value                        // prevents this from compiling.)Silly this may be, but not so silly that it's prohibited for the built-in types: int i1, i2, i3;...(i1 = i2) = i3;                // legal! assigns i2 to                               // i1, then i3 to i1!I know of no practical use for this kind of thing, but if it's good enough for the ints, it's good enough for me and my classes. It should be good enough for you and yours, too. Why introduce gratuitous incompatibilities with the conventions followed by the built-in types?Within an assignment operator bearing the default signature, there are two obvious candidates for the object to be returned: the object on the left hand side of the assignment (the one pointed to by this) and the object on the right-hand side (the one named in the parameter list). Which is correct?Here are the possibilities for a String class (a class for which you'd definitely want to write an assignment operator, as explained in Item 11): String& String::operator=(const String& rhs){  ...  return *this;            // return reference                           // to left-hand object}String& String::operator=(const String& rhs){  ...  return rhs;              // return reference to                           // right-hand object}This might strike you as a case of six of one versus a half a dozen of the other, but there are important differences.First, the version returning rhs won't compile. That's because rhs is a reference-to-const-String, but operator= returns a reference-to-String. Compilers will give you no end of grief for trying to return a reference-to-non-const when the object itself is const. That seems easy enough to get around, however just redeclare operator= like this: String& String::operator=(String& rhs)   { ... }Alas, now the client code won't compile! Look again at the last part of the original chain of assignments: x = "Hello";                     // same as x.op=("Hello");Because the right-hand argument of the assignment is not of the correct type it's a char array, not a String compilers would have to create a temporary String object (via the String constructor see Item M19) to make the call succeed. That is, they'd have to generate code roughly equivalent to this: const String temp("Hello");      // create temporaryx = temp;                        // pass temporary to op=Compilers are willing to create such a temporary (unless the needed constructor is explicit see Item 19), but note that the temporary object is const. This is important, because it prevents you from accidentally passing a temporary into a function that modifies its parameter. If that were allowed, programmers would be surprised to find that only the compiler-generated temporary was modified, not the argument they actually provided at the call site. (We know this for a fact, because early versions of C++ allowed these kinds of temporaries to be generated, passed, and modified, and the result was a lot of surprised programmers.)Now we can see why the client code above won't compile if String's operator= is declared to take a reference-to-non-const String: it's never legal to pass a const object to a function that fails to declare the corresponding parameter const. That's just simple const-correctness.You thus find yourself in the happy circumstance of having no choice whatsoever: you'll always want to define your assignment operators in such a way that they return a reference to their left-hand argument, *this. If you do anything else, you prevent chains of assignments, you prevent implicit type conversions at call sites, or both. Back to Item 15: Have operator= return a reference to *this.Continue to Item 17: Check for assignment to self in operator=.Item 16: Assign to all data members in operator=.Item 45 explains that C++ will write an assignment operator for you if you don't declare one yourself, and Item 11 describes why you often won't much care for the one it writes for you, so perhaps you're wondering if you can somehow have the best of both worlds, whereby you let C++ generate a default assignment operator and you selectively override those parts you don't like. No such luck. If you want to take control of any part of the assignment process, you must do the entire thing yourself.In practice, this means that you need to assign to every data member of your object when you write your assignment operator(s): template<class T>          // template for classes associatingclass NamedPtr {           // names with pointers (from Item 12)public:  NamedPtr(const string& initName, T *initPtr);  NamedPtr& operator=(const NamedPtr& rhs);private:  string name;  T *ptr;};template<class T>NamedPtr<T>& NamedPtr<T>::operator=(const NamedPtr<T>& rhs){  if (this == &rhs)    return *this;              // see Item 17  // assign to all data members  name = rhs.name;             // assign to name  *ptr = *rhs.ptr;             // for ptr, assign what's                               // pointed to, not the                               // pointer itself  return *this;                // see Item 15}This is easy enough to remember when the class is originally written, but it's equally important that the assignment operator(s) be updated if new data members are added to the class. For example, if you decide to upgrade the NamedPtr template to carry a timestamp marking when the name was last changed, you'll have to add a new data member, and this will require updating the constructor(s) as well as the assignment operator(s). In the hustle and bustle of upgrading a class and adding new member functions, etc., it's easy to let this kind of thing slip your mind.The real fun begins when inheritance joins the party, because a derived class's assignment operator(s) must also handle assignment of its base class members! Consider this: class Base {public:  Base(int initialValue = 0): x(initialValue) {}private:  int x;};class Derived: public Base {public:  Derived(int initialValue)  : Base(initialValue), y(initialValue)   {}  Derived& operator=(const Derived& rhs);private:  int y;};The logical way to write Derived's assignment operator is like this: // erroneous assignment operatorDerived& Derived::operator=(const Derived& rhs){  if (this == &rhs) return *this;    // see Item 17  y = rhs.y;                         // assign to Derived's                                     // lone data member  return *this;                      // see Item 15}Unfortunately, this is incorrect, because the data member x in the Base part of a Derived object is unaffected by this assignment operator. For example, consider this code fragment: void assignmentTester(){  Derived d1(0);                      // d1.x = 0, d1.y = 0  Derived d2(1);                      // d2.x = 1, d2.y = 1  d1 = d2;			      // d1.x = 0, d1.y = 1!}Notice how the Base part of d1 is unchanged by the assignment.The straightforward way to fix this problem would be to make an assignment to x in Derived::operator=. Unfortunately, that's not legal, because x is a private member of Base. Instead, you have to make an explicit assignment to the Base part of Derived from inside Derived's assignment operator.

⌨️ 快捷键说明

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