c++ 基础知识-类和对象-运算符重载2
1.赋值运算符重载
# include <iostream>
# include <string>
using namespace std;
class Int
{
public :
Int ( int i) ;
~ Int ( ) ;
int * m_Int;
Int& operator = ( Int & i)
{
if ( m_Int != NULL )
{
delete m_Int;
m_Int = NULL ;
}
m_Int = new int ( * i. m_Int) ;
return * this ;
}
} ;
Int :: Int ( int i)
{
m_Int = new int ( i) ;
}
Int :: ~ Int ( )
{
if ( m_Int != NULL )
{
delete m_Int;
m_Int = NULL ;
}
cout<< "析构函数" << endl;
}
void fun ( )
{
Int i1 ( 10 ) ;
cout<< * i1. m_Int<< endl;
Int i2 ( 20 ) ;
i2 = i1;
cout<< * i2. m_Int<< endl;
Int i3 ( 40 ) ;
i3 = i2 = i1;
cout<< * i3. m_Int<< endl;
}
int main ( )
{
fun ( ) ;
return 0 ;
}
2.关系运算符重载
# include <iostream>
# include <string>
using namespace std;
class Int
{
public :
Int ( int i) ;
~ Int ( ) ;
int m_int;
bool operator == ( Int & i)
{
if ( this -> m_int == i. m_int)
{
return true ;
}
return false ;
}
} ;
Int :: Int ( int i)
{
m_int = i;
}
Int :: ~ Int ( )
{
cout<< "析构函数" << endl;
}
void fun ( )
{
Int i1 ( 23 ) ;
Int i2 ( 34 ) ;
if ( i1 == i2)
{
cout<< "Equal !!!" << endl;
} else {
cout<< "No equal !!!" << endl;
}
}
int main ( )
{
fun ( ) ;
return 0 ;
}
3.函数调用运算符重载
# include <iostream>
# include <string>
using namespace std;
class Int
{
public :
Int ( int i) ;
~ Int ( ) ;
int m_int;
int operator ( ) ( )
{
return m_int;
}
} ;
Int :: Int ( int i)
{
m_int = i;
}
Int :: ~ Int ( )
{
cout<< "析构函数" << endl;
}
void fun ( )
{
Int i1 ( 23 ) ;
Int i2 ( 34 ) ;
cout<< i2 ( ) << endl;
cout<< Int ( 123 ) ( ) << endl;
}
int main ( )
{
fun ( ) ;
return 0 ;
}