摘要:The solution is to replace the pointer pa with an object that acts like a pointer. That way, when the pointer-like object is (automatically) destroyed, we can have its destructor call delete. Objects that act like pointers, but do more, are called smart pointers, and, as Item 28 explains, you can m.
阅读全文
摘要:Though you want to create an object on the heap, use the new operator. It both allocates memory and calls a constructor for the object. If you only want to allocate memory, call operator new; no constructor will be called. If you want to customize the memory allocation that takes place when heap ob.
阅读全文
摘要:The purpose of operator overloading is to make programs easier to read, write, and understand, not to dazzle others with your knowledge that comma is an operator. If you don't have a good reason for overloading an operator, don't overload it. In the case of &&, ||, and ,, it's di
阅读全文
摘要:1#include<iostream>2usingnamespacestd;34classMyInt5{6private:7inta;8public:9MyInt(intn):a(n){};1011MyInt&operator++()12{13a+=1;14return*this;15};1617constMyIntoperator++(int)18{19MyIntold=*this;20++(*this);2122returnold;23};2425intgetValue()26{27returna;28}29};3031intmain()32{33MyInti(4);3
阅读全文
摘要:Two kinds of functions allow compilers to perform such conversions: single-argument constructors and implicit type conversion operators. A single-argument constructor is a constructor that may be called with only one argument. Such a constructor may declare a single parameter or it may declare mult.
阅读全文
摘要:1#include<iostream>2usingnamespacestd;34classA5{6private:7inta;8public:9A(intn):a(n){}10};1112intmain()13{14void*rawMemory=operatornew[](10*sizeof(A));1516A*a=static_cast<A*>(rawMemory);1718A*arrayOfA[10];19for(inti=0;i<10;i++)20{21new(&arrayOfA[i])A(i);22}2324for(inti=0;i<10;i
阅读全文
摘要:1#include<iostream>23usingnamespacestd;45classBST6{7private:8inta;910public:11BST(intn):a(n){};12intgetData(){returna;}13friendostream&operator<<(ostream&os,BST&bst);14};1516ostream&operator<<(ostream&os,BST&bst)17{18cout<<bst.getData();19returnos;20}2
阅读全文
摘要:static_cast has basically the same power and meaning as the general-purpose C-style cast. It also has the same kind of restrictions. For example, you can't cast a struct into an int or a double into a pointer using static_cast any more than you can with a C-style cast. Furthermore, static_cast c
阅读全文
摘要:First, recognize that there is no such thing as a null reference. A reference must always refer to some object. As a result, if you have a variable whose purpose is to refer to another object, but it is possible that there might not be an object to refer to, you should make the variable a pointer, .
阅读全文