C ++ copy constructor and operator overload

Source: Internet
Author: User

Duplicate copying constructor and operator

* Polymorphism

-Front dike: inheritance, virtual function, pointer or reference

-Type conversion: dynamic_cast converts the parent class * To a subclass *

-Pure virtual function: This function is not executed. It is an abstract class and cannot be used to create objects.

 

* Youyuan

-Internal authorization is not a member. This is very important, so there is no such thing as this.

 

No.

-To break the encapsulation, there must be an internal declaration of the class to access any member through the object.

 

Q.

 

* Static

-Is a member

-A member is shared by all members of the entire class.

-Static data member: initialized externally

-Static functions can only access static members. Class Name: Member

========================================================== ================

* Operator Overloading (Special Functions of C ++)

* Internal class

* Exception

 

The copy constructor has nothing special except its name.

C ++ code

A (const A & OBJ ){

Cout <"I Am a copy constructor" <Endl;

}

A A = OBJ // It is equivalent to a A (OBJ)

 

 

C ++ code

# Include <iostream>

Using namespace STD;

 

Class {

Int data;

Public:

A (): Data (5) {// The initialization list initializes members rather than parameters.

Cout <"A ()" <Endl;

}

A (int d): Data (d ){

Cout <"A (INT)" <Endl;

}

A (bool B): Data (B? 12:234 ){

Cout <"A (bool)" <Endl;

}

A (char C): Data (INT) c ){

Cout <"A (char)" <Endl;

}

A (const A & O): Data (O. Data ){

Cout <"A (const A &)" <Endl;

}

Void show (){

Cout <"Data =" <data <Endl;

}

Virtual ~ A (){

Cout <"~ A () "<Endl;

}

};

Int main ()

{

A A1; // call a constructor without Parameters

A A2 (28 );

A A3 (true );

A A4 ('s ');

A A5 (A2 );

}

 

// Advantages of using references

# Include <iostream>

Using namespace STD;

 

Class {

Int data;

Public:

A (): Data (5) {// The initialization list initializes members rather than parameters.

Cout <"A ()" <Endl;

}

A (int d): Data (d ){

Cout <"A (INT)" <Endl;

}

A (bool B): Data (B? 12:234 ){

Cout <"A (bool)" <Endl;

}

A (char C): Data (INT) c ){

Cout <"A (char)" <Endl;

}

// A (const A & O): Data (O. Data ){

// Cout <"A (const A &)" <Endl;

//}

// The form parameter is a new variable. It is created during the call and initialized by the real parameter.

A (a o): Data (O. Data) {// This write is incorrect and enters an endless loop.

Cout <"A (const A &)" <Endl;

}

// When creating an object, you must call the constructor to create an object. The constructor is a new object,

// Create a new object and call the constructor. Call the constructor to create a parameter ,.......

Void show () const {

Cout <"Data =" <data <Endl;

}

Virtual ~ A (){

Cout <"~ A () "<Endl;

// Show (200 );

// Show (false );

// Show ('A ');

// A A2 (28 );

// A A3 (true );

// A A4 ('s ');

// A A5 (A2 );

}

};

Void show (a obj)

{

OBJ. Show ();

}

Void func (const A & OBJ)

{

OBJ. Show ();

}

Int main ()

{

A A1; // call a constructor without Parameters

Show (A1 );

Func (A1 );

}

 

 

 

When the class has no constructor, A (), A (const A &) constructor is automatically generated.

 

+ When a class member has pointer members pointing to the dynamic memory, the default copy constructor may fail.

It causes confusion when two pointers point to the same place.

In this case, we need to rewrite this copy constructor. the following example:

C ++ code

# Include <iostream>

Using namespace STD;

 

Class {

Int data;

Public:

A (): Data (5) {// The initialization list initializes members rather than parameters.

Cout <"A ()" <Endl;

}

// Copy the constructor

A (const A & O)/*: Data (O. Data )*/{

Cout <"A (const A &)" <Endl;

}

Void show (){

Cout <"Data =" <data <Endl;

}

Virtual ~ A (){

Cout <"~ A () "<Endl;

}

};

Int main ()

{

A A1;

A1.show (); // The output is normal.

A A2 (A1 );

A2.show (); // output junk data, so initialization should not be less

}

 

You can access any member variables in the class in the member functions of the class.

 

After you define the copy constructor, there will be no default copy constructor.

 

The custom copy constructor processes all the data to be processed.

 

 

C ++ code

// Dynamic array class, the length can be dynamically changed. Not full

# Include <iostream>

Using namespace STD;

 

Class Array {

Char * P;

Int Len;

Public:

Array (int n): Len (N), P (null ){

Resize (N );

}

Array (const array & O): Len (O. Len ){

P = new char [Len];

For (INT I = 0; I <Len; I ++)

P [I] = O. P [I];

}

Void resize (int n ){

Char * q = new char [N];

Int min = (n <Len? N: Len );

If (P! = NULL ){

For (INT I = 0; I <min; I ++)

Q [I] = P [I];

Delete [] P;

}

P = Q;

For (INT I = min; I <n; I ++)

P [I] = '/0 ';

Len = N;

}

Int size (){

Return Len;

}

Void set (INT index, char c ){

If (index <0 | index> Len ){

Cout <"error" <Endl;

Return;

}

P [Index] = C;

}

Char get (INT index ){

If (index <0 | index> Len ){

Cout <"error" <Endl;

Return '^ ';

}

Return P [Index];

}

Void fill (char start, int skip ){

For (INT I = 0; I <Len; I ++)

P [I] = start + I * Skip;

}

Void show (){

For (INT I = 0; I <Len; I ++ ){

Cout <p [I];

}

}

~ Array (){

If (P! = NULL ){

Delete [] P;

P = NULL;

}

}

}; // End class Array

 

Int main ()

{

Array A1 (10 );

A1.fill ('A', 2 );

A1.show ();

Cout <Endl;

Array A2 (A1 );

A2.fill ('A', 2 );

A2.show ();

Cout <Endl;

A1.show ();

Cout <Endl;

Cout <"------------------" <Endl;

Cout <"Please input text (end by '$'):" <Endl;

For (INT I = 0; I ++ ){

Char C;

Cin> C;

If (C = '$ ')

Break;

Else if (I + 1> a1.size ()){

A1.resize (a1.size () + 10 );

}

A1.set (I, C );

}

A1.show ();

Cout <Endl;

For (INT I = 0; I <a1.size (); I ++ ){

Cout <a1.get (I );

}

}

 

==========================================================

 

The default copy constructor is a shortest copy function, and the self-written copy constructor is a deep copy function.

 

* Operator Functions

* Single object Operator

 

C ++ code

A operator + (A obj1, aobj2) {/* Code */};

 

A A1 (30), A2 (50 );

A result;

Result = A1 + A2; // calls a operator + (A obj1, aobj2)

Result. Show ();

 

C ++ code

// Example

// The program shows that the member is more convenient than the Member, and one parameter is missing.

# Include <iostream>

Using namespace STD;

Class {

// Code

A sub (const A & O ){

Return A (data-o.data );

}

A oprator -()/......

};

A operator-(const A & O1, const A & O2 ){

 

// Code...

}

Int main ()

{

A obj1 (40), obj2 (50 );

A obj3, obj4;

Obj3 = obj1.sub (obj2 );

Obj3.show ();

Obj4 = obj1-obj2; // calls obj1.aperator -(..)

}

 

 

Operator Overloading means writing operator functions to define how operators work.

 

--------------------------

Implementation of operator functions:

* Youyuan operator functions:

-Declare friend in the class

-Definition: return type operatorx (parameter 1, parameter 2)

-Call: obj1 x obj2 is interpreted as operatorx (obj1, obj2 ).

 

Calculation Result

* Member functions: defined directly in the class

-Definition: return type operatorx (parameter 1)

-Call: obj1 x obj2 is interpreted as obj1.operator (obj2), and the return value is used as an operation.

 

Result

 

Cout <F1 <F2; // represents using overload operators. It can only be implemented by friends.

// If you want to use a member function, there will be cout. Operator <(const F & F), so this is not

 

// Possible. Therefore, it can only be implemented by friends. Operator <(cout, F)

// Cout is ostream type, so there are the following standard formats. Note that const cannot be added because //

 

Cout is to be changed and will change the buffer members.

Ostream & operator <(/* cannot add const */ostream & cout, const

 

F &) // the standard format of the output operator.

Friend istream & operator> (istream & is, F & F ){

 

} // Enter the operator to overload the standard format

 

C ++ code

// Complete example of heavy-duty operators

// Binary operator overload

# Include <iostream>

Using namespace STD;

Class F {

Int N;

Int D;

Public:

F (INT n = 0, int d = 1): n (n), D (d ){}

Friend ostream & operator <(ostream & OS, const F & F ){

OS <'[' <F. N <'/' <F. D <']';

Return OS;

}

F operator * (const F & O ){

Return F (N * O. N, D * o. D );

}

Friend F operator/(const F & F1, const F & F2 ){

Return F (f1.n * f2.d, f1.d * f2.n );

}

Friend istream & operator> (istream & is, F & F ){

Char ch;

Is> F. N> CH> F. D;

Return is;

}

};

 

Int main ()

{

F F1 (3, 5), F2 (11, 7), F;

Cout <F1 <'*' <F2 <'=' <F1 * F2 <Endl;

Cout <F1 <'/' <F2 <'=' <F1/F2 <Endl;

Cout <"input 2 fractions :";

Cin> F1> F2;

Cout <"f1 =" <F1 <Endl;

Cout <"f2 =" <F2 <Endl;

}

 

 

* Single object operator overload

-In the form of a youyuan function, operatorx (parameter) is returned)

Use: x obj ---> operatorx (OBJ );

-Use operatorx (/* intangible parameter */) returned by members as much as possible in the form of member functions */)

Use: x obj ---> obj. Operator ();

 

C ++ code

// Single object operator overload

// Use the suffix ++ and suffix -- as the binary operator, and the second operand is an integer.

# Include <iostream>

Using namespace STD;

 

Class {

Int data;

Public:

A (int d = 0): Data (d ){}

Friend ostream & operator <(ostream & OS, const A & ){

OS <A. Data;

Return OS;

}

Friend istream & operator> (istream & is, A & ){

Is> A. Data;

Return is;

}

Friend a & operator ++ (A & ){

A. Data + = 10;

Return;

}

A & operator --(){

Data-= 10;

Return * this;

}

// Add the following parameter to specify an integer as a parameter.

Friend a/* No reference */operator ++ (A & A, INT ){

A old ();

A. Data + = 1;

Return old;

}

// Subtraction after subtraction, which must be an integer and differentiated from Subtraction first.

A/* Do not reference */operator -- (INT ){

A old (* This );

Data-= 1;

Return old;

}

};

 

Int main ()

{

A A1 (50), A2 (100 );

Cout <"a1 =" <A1 <Endl;

Cout <"A2 =" <A2 <Endl;

Cout <"++ a1 =" <++ A1 <Endl;

Cout <"-- a1 =" <-- A1 <Endl;

Cout <"A1 ++ =" <A1 ++ <Endl;

Cout <"a1 =" <A1 <Endl;

Cout <"A2 -- =" <A2 -- <Endl;

Cout <"A2 =" <A2 <Endl;

 

}

 

 

Operator overloading provides a method for specifying the operator method, at least one operation

 

The number of operations is a custom type. We cannot specify the basic type.

Forced type conversion: type (data) --> (you do not need to write the return type, because it is always consistent with the following class

 

Type is the same) operator type (intangible parameter) can only be written as a member function, not a friend.

 

C ++ code

# Include <iostream>

Using namespace STD;

 

Class {

Int data;

Public:

A (int d = 0): Data (d ){}

Operator int (){

Return data;

}

Operator bool (){

Return data! = 0;

}

Operator char (){

Return (char) data;

}

};

Int main ()

{

A A1 (65), A2 (200 );

Cout <"a1 =" <(char) A1 <Endl;

Int d = a2;

If (A2)

Cout <"good" <Endl;

}

 

When using operators for custom objects, the corresponding operators and functions are always called.

 

The three-object operator cannot be overloaded.

The equal sign is a binary operator and can be overloaded. It can only be a member.

The periods ('.') cannot be reloaded.

Double colons (: :) cannot be overloaded.

Sizeof (type) cannot be overloaded.

# The number is not an operator and does not matter if it is overloaded.

'= () []-> Type conversion' can only be reloaded by member functions. For other functions, we recommend that you try

 

You can use member functions to write data, such as input and output.

========================================================== ============

+ Binocular Operator Overloading

-Youyuan format: Return operator symbol (shape 1, shape 2)

-Member form: Return operator symbol (form)

+ Single object operator overload

-Youyuan: Return operator symbol (parameter)

-Member: Return operator symbol ()

+ Special Case

-Add

-Add first

-Add the return operator symbol (shape, INT)

-Subtraction

-Subtract first

-Subtraction

-Type conversion can only be a member's perator space type ();

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.