Each class, the compiler will automatically generate four special member functions:
- destructor (destructor)
- Default constructor (constructor)
- Copy constructor (copy constructor)
- Copy Assignment
operator =(copy assignment操作符)
But sometimes we don't want to have some default constructors for the class we're designing. Then we should explicitly forbid it.
For example, I designed a class that does not want the copy constructor and the copy assignment operator, so I can declare these two functions as private and deliberately do not implement them.
class Zywscq () {public: zywscq () {} ~zywscq () {}private: ZYWSCQ (const zywscq&); // only declarations operator= (const zywscq&); // anyway, don't bother to write parameter name. }
In fact, C++11 provides a better approach: Add "=delete" after the function declaration, you can disable the function.
classx{ Public: X (); X (Constx&) =Delete;//declare copy constructor as deleted functionx&operator= (ConstX &) =Delete;//Declaration Copy assignment operator is deleted function }; intMain () {X x1; X X2=x1;//error, copy constructor disabledX x3; X3=x1;//error, copy assignment operator is disabled}
How C + + rejects compiler auto-generated functions