#include <iostream>
#include <string>
using namespace std;
class Num
{
friend ostream& operator<<(ostream&, Num&);
friend istream& operator>>(istream&, Num&);
public:
Num(){}
Num(int a ,int b):m_Numb(new int(0)),m_Numa(0)
{
m_Numa = a;
m_Numb = new int(b);
}
~Num()
{
if (m_Numb != NULL)
{
delete m_Numb;
m_Numb = NULL;
}
}
//重载+
Num operator+(Num &n)
{
Num x;
x.m_Numa = this->m_Numa + n.m_Numa;
return x;
}
//重载-
Num operator-(Num &n)
{
Num x;
x.m_Numa = this->m_Numa - n.m_Numa;
return x;
}
//前置递增递减
Num & operator++()
{
++this->m_Numa;
return *this;
}
Num & operator--()
{
--this->m_Numa;
return *this;
}
//后置递增递减
Num operator++(int)
{
Num temp = *this;
++m_Numa;
return temp;
}
Num operator--(int)
{
Num temp = *this;
--m_Numa;
return temp;
}
//赋值运算符
Num & operator=(Num & p)
{
//判断是否为空
if (m_Numb != NULL)
{
delete m_Numb;
m_Numb = NULL;
}
//进行深拷贝操作
m_Numb = new int(*p.m_Numb);
return *this;
}
int *m_Numb;
//关系运算符
bool operator == (Num & p)
{
if (this->m_Numa == p.m_Numa && *this->m_Numb == *p.m_Numb)
{
return true;
}
else
{
return false;
}
}
//括号运算符
void operator()(string x)
{
cout << x << endl;
}
private:
int m_Numa;
};
//重载输入输出流运算符
ostream& operator<<(ostream &out, Num &s)
{
out << "m_Numa=" << s.m_Numa << endl;
return out;
}
istream& operator>>(istream &in, Num &s)
{
in >> s.m_Numa;
return in;
}
//输入输出以及加减重载测试
void test1()
{
Num n1, n2;
cout << "请输入对象值:";
cin >> n1 >> n2;
Num n3 = n1 + n2;
cout << n3;
Num n4 = n1 - n2;
cout << n4;;
}
//递增递减重载测试
void test2()
{
Num n;
cin >> n;
cout << ++n;
n--;
cout << n;
}
//赋值运算符重载测试
void test3()
{
Num n1(0,10);
Num n2(0,20);
Num n3(0,30);
n1 = n2 = n3;
cout << *n1.m_Numb << endl;
cout << *n2.m_Numb << endl;
cout << *n3.m_Numb << endl;
}
//关系运算符重载测试
void test4()
{
Num n1(10,10),n2(10,10);
if (n1 == n2)
{
cout << "相等" << endl;
}
else
{
cout << "不等" << endl;
}
}
//括号运算符重载测试
void test5()
{
Num n;
n("Hello word!");
}
int main()
{
system("pause");
return 0;
}
C++:运算符重载(详)
最新推荐文章于 2023-06-08 22:09:33 发布