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