[C/C ++] Reload the constructor of another class in one class ---- constructor is a special operator

Source: Internet
Author: User

Suppose we have two classes A and B.

[Cpp]
Class
{
Public:
A (int n): a (n ){}
Void Print () {cout <a <endl ;}
Private:
Int;
};
 
 
 
Class B
{Www.2cto.com
Public:
Void SetVal (int a) {B = ;}
Private:
Int B;
};

When you need to construct an object of Class A using an object of Class B, the following constructor can be defined in Class:

[Cpp]
A (B );
However, this constructor cannot be defined in the following situations:

1. assign A value to A using the private member of B, and B does not define A as A friend class;

2. You have no permission to modify the definition of A. You can only modify B.

Here, we need to treat the constructor of A as A special operator and reload this operator in the definition of Class B.

[Cpp]
Class B
{
Public:
Operator A () const
{
Return A (B );
}
Void SetVal (int a) {B = ;}
Private:
Int B;
};

After the overload, where A is required as the parameter and B is put, the overload operator A () of B is called implicitly to construct an object of Class.
For example:

[Cpp]
A objA (objB );
 
Vector <A> vecA;
VecA. push_back (objB );
Complete code example:

[Cpp]
# Include <iostream>
# Include <string>
# Include <vector>
Using namespace std;
 
Class
{
Public:
A (int n): a (n ){}
Void Print () {cout <a <endl ;}
Private:
Int;
};
 
 
 
Class B
{
Public:
Operator A () const
{
Return A (B );
}
Void SetVal (int a) {B = ;}
Private:
Int B;
};
 
 
Int main ()
{
B objB;
ObjB. SetVal (5 );
A objA (objB );
ObjA. Print ();
 
ObjB. SetVal (10 );
Vector <A> vecA;
VecA. push_back (objB );
VecA [0]. Print ();
 
Return 0;
}
Output result:

5

10

Related Article

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.