c++ 基础知识-类和对象-运算符重载2
1.赋值运算符重载
#include
#include
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<<"析构函数"<
Int i1(10);
cout<<*i1.m_Int<
fun();
//输出
//10
//10
//10
//析构函数
//析构函数
//析构函数
return 0;
}
2.关系运算符重载
#include
#include
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<<"析构函数"<
Int i1(23);
Int i2(34);
if(i1 == i2)
{
cout<<"Equal !!!"<
cout<<"No equal !!!"<
fun();
return 0;
}
3.函数调用运算符重载
#include
#include
using namespace std;
class Int
{
public:
Int(int i);//构造函数
~Int();//析构函数
int m_int;
//重载函数运算符号
int operator()()
{
//cout<
m_int = i;
}
Int::~Int()
{
cout<<"析构函数"<
Int i1(23);
Int i2(34);
cout<
fun();
return 0;
}