' C + + ' operator overloading

Source: Internet
Author: User

FAQ

Q1. The following operators, which cannot be overloaded in the C + + language, are ().

A. * B.?: C.:: D. Delete

Q2. Write a constructor, destructor, and assignment function for a class string.

Q3. What is the difference between a copy constructor and an assignment operator?

Q4. What is the output of the following code?

1#include <iostream>2 using namespacestd;3 classX4 {5  Public:6X () {cout <<"Constructor"<<Endl;}7     Static void*operator New(size_t size)8     {9cout <<"New"<<Endl;Ten         return::operator New(size); One     } A     Static void operator Delete(void*pointee) -     { -cout <<"Delete"<<Endl; the::operator Delete(pointee); -     } -~x () {cout <<"destructor"<<Endl;} - };  + intMain () - { +X * px =NewX (); A     Deletepx; at     return 0;  -}

Q5. How can I restrict the generation of stack objects? How can I limit the build of a heap object?

operator Overloading

The operator overloaded function has the name operator followed by the symbol of the operator that is defined. Like any other function, the operator overload function has a return value and a formal parameter list. The formal parameter list must have the same parameters as the number of operators (if the operator is a class member, the implicit this parameter is included). For example, the assignment is a two-dollar operation, so the operator function has two parameters: the first parameter corresponds to the left operand, and the second parameter corresponds to the right operand.

Most operators can be defined as member functions or non-member functions. When the operator is a member function, its first operand is implicitly bound to the this pointer. Some operators, including assignment operators, must be member functions of a class. For example, an assignment must be a member of a class, so this is bound to a pointer to the left operand. Therefore, the assignment operator accepts a single parameter, and the parameter is an object of the same class type. The right operand is generally passed as a const reference.

1. Can be overloaded with operators

Most operators can be overloaded, but not all operators can be overloaded. The following four operators cannot be overloaded:

::  .*  . ?:

A simple summary: "dot" can not be overloaded .

2. Assignment operator overloading

"Example" is known as the prototype of the string class, writing the constructor, destructor, and assignment functions of the class string.

1 classString2 {3  Public:4     //Common Constructors5String (Const Char*str =NULL); 6     //copy Constructor7String (ConstString &Other ); 8     // Destructors9~String ();Ten     //Assignment Function OneString &operator= (ConstString &Other );  A Private: -     //used to save strings -     Char*m_data; the};

(1) a destructor for String

To prevent a memory leak, we need to define a destructor. When a string object is outside its scope, the destructor frees the memory it occupies. The code is as follows:

1 string::~String ()2{3     Delete4     //  5 }

(2) constructor of string

This constructor can help us to create a string object based on one of the strings constants. This constructor allocates a sufficient amount of memory first, and then copies the string constant to this memory, the code is as follows:

1String::string (Const Char*str)2 {3     if(str = = NULL)//It's better if you can add a null judgment .4     {5M_data =New Char[1]; 6     }7     Else 8     {9         intLength =strlen (str);TenM_data =New Char[Length +1];//Think about why you add 1 . One strcpy (m_data, str); A     } -}

The Strlen function returns the actual number of characters for this string constant (excluding the null terminator), and then assigned all the characters of the string constant to the memory that we have allocated for the M_data data member during the string object creation. With this constructor, we can create a new string object based on a string constant as follows:

String str ("Hello");

(3) copy constructor for string

All user-defined types that need to allocate system resources require a copy constructor. The copy constructor also helps us pass a string argument as a value in a function call, and implements "copy on return" When a function returns a String object as a value.

1String::string (ConstString &Other )2 {3     if(Other.m_data = =NULL)4     {5M_data =New Char[1]; 6     }7     Else 8     {9         intLength =strlen (other.m_data);TenM_data =New Char[Length +1];  One strcpy (m_data, str); A     } -}

(4) Assignment function of string

The assignment function code looks like this:

String & string::operator= (ConstString &Other ) {    if( This= = &other)//Check self-assigned value        return* This; Delete[] m_data;//freeing up legacy memory resources    intLength =strlen (Other.m_data); M_data=New Char[Length +1];//allocating a new memory resourcestrcpy (m_data, other.m_data); return* This; }

  Assignment operator overloading requires attention:

A. Whether to declare the type of the return value as a reference to that type, and return a reference to the instance itself before the function ends. This is the only way to allow continuous assignment of values. Otherwise, if the return value of the function is void, assume that there are three string objects, STR1, str2, and STR3, in the program the statement str1 = STR2 = STR3 will not be compiled.

B. Whether to declare the type of the passed-in parameter as a constant reference. If the passed parameter is not a reference but an instance, the copy constructor is called once from the formal parameter to the actual delegate. Declaring a parameter as a reference avoids such unnecessary consumption and can improve the efficiency of the Code. Also, we do not change the state of the incoming instance within the assignment operator function, so we should add the Const keyword to the incoming reference parameter.

C. Remember to release the memory of the instance itself. If you forget to release your existing space before allocating new memory, a memory leak will occur.

D. Whether the passed parameter is judged to be the same instance as the current instance (*this). If it is the same, the assignment is not performed and is returned directly. If the assignment is done without prior judgment, then it can cause serious problems when releasing the memory of the instance itself: when the *this and the passed arguments are the same instance, once the memory is freed, the memory of the incoming parameter is also freed, so no more content is found to be assigned.

3. Overloading of output operators <<

4. Overloads of operator new and operator delete

' C + + ' operator overloading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.