Do Assignment Operator Conversion
You will find interesting. I want to convert from object B to object
A and I have to use vector.
vector< A > a;
vector< B > b;
a = b;
You can't do that because vector does not have assignment operator
implementation. What will you do?
Create class A and class B. Both class A and class B are derived
from vector. All the functions of vector are inherited into class A
and class B.
template< typename U >
class B;
template< typename T >
class A : public vector< T > {
public:
template< typename U >
A< T >& operator =( const B< U >& );
};
template< typename T >
class B : public vector< T > {
public:
};
template< typename T >
template< typename U >
A< T > &A< T >::operator =( const B< U > &right ) {
A< T >::iterator iterA = begin();
B< U >::const_iterator iterB = right.begin();
while( iterA != end() ) {
*iterA = *iterB; // sample only
// convertData( iterA, iterB ); // not implemented yet
iterA++;
iterB++;
}
return *this;
}
int main() {
A< int > a;
B< int > b;
a.push_back( 1 );
a.push_back( 2 );
a.push_back( 3 );
a.push_back( 4 );
b.push_back( 10 );
b.push_back( 20 );
b.push_back( 30 );
b.push_back( 40 );
a = b;
return 0;
}
You already know that string is an example. It has a function to
convert from char* to string.
What if you want to convert from string to any type of object?
Think of class A is to be named pixelString and class B is to be
named string. You can do either two ways.
pixelString pixelStrName_A = =93There is a cat sitting on the fence.=94;
or=85
pixelString pixelStrName_A;
string strName_B = =93There is a cat sitting on the fence.=94;
pixelStringName_A = strName_B;
Each character in the string will be converted to pixelString before
pixelString calls a function to draw 16 x 16 bitmap. You can modify
string and then bitmap will be redrawn automatically.