- 什么是运算符重载
- 赋予运算符具有操作自定义类型数据功能
- 运算符重载的实质是什么?
- 运算符重载的实质本身就是函数调用
- 运算符重载函数的写法
- 函数返回值 函数名(函数参数)
- 函数返回值 :运算完成后的值决定的 Complex
- 函数名 : operator 加上重载运算符组成函数名 operator+
- 参数 :看运算符的操作数,具体参数个数是要看你重载函数形式是什么
- 函数体 : 写运算符具体想要的操作
运算符类成员函数重载,参数个数等于操作减一
#include<iostream>
using namespace std;
class Int
{
public:
Int()= default;
Int(int m_num) :m_num(m_num){}
void print()
{
cout << m_num << endl;
}
Int operator+(const Int& data)
{
return Int(this->m_num + data.m_num);
}
protected:
int m_num;
};
int main()
{
Int A(20);
Int B(30);
Int C;
C = B + A;
C.print();
return 0;
}
运算符友元重载,参数个数就是操作数据
#include<iostream>
using namespace std;
class Int
{
public:
Int()= default;
Int(int m_num) :m_num(m_num){}
void print()
{
cout << m_num << endl;
}
friend Int operator+(Int A, Int B);
protected:
int m_num;
};
Int operator-(Int A, Int B)
{
return Int(A.m_num + B.m_num);
}
int main()
{
Int A(20);
Int B(30);
Int C;
C = B + A;
C.print();
return 0;
}
特殊运算符重载
- 流运算符重载
- cin类型 :istream类的对象
- cout类型:ostream类的对象
- 流运算符 >> <<
- 流重载必须采用友元函数形式重载
输入流对象
#include<iostream>
#include<string>
using namespace std;
class MM
{
public:
MM(string name="", int age=18) :name(name), age(age) {}
public:
friend istream& operator>>(istream& in, MM& mm);
protected:
string name;
int age;
};
istream& operator>>(istream& in, MM& mm)
{
in >> mm.name >> mm.age;
return in;
}
int main()
{
MM mm;
cin >> mm;
return 0;
}
输出流对象
#include<iostream>
#include<string>
using namespace std;
class MM
{
public:
MM(string name="", int age=18) :name(name), age(age) {}
public:
friend ostream& operator<<(ostream& out, MM& mm);
protected:
string name;
int age;
};
ostream& operator<<(ostream& out, MM& mm)
{
out << mm.name << "\t" << mm.age << endl;
return out;
}
int main()
{
MM mm;
cout << mm;
return 0;
}
++ --运算符重载
- 解决问题:前置和后置的问题:增加无用参数 int去表示当前运算符重载是后置操作
#include<iostream>
#include<string>
using namespace std;
class MM
{
public:
MM(string name, int age) :name(name), age(age) {}
friend ostream& operator<<(ostream&out, MM& mm)
{
cout << mm.name << "\t" << mm.age << endl;
return out;
}
MM operator++(int)
{
return MM(name, age++);
}
MM operator++()
{
return MM(name,++age);
}
protected:
string name;
int age;
};
int main()
{
MM mm("小芳",18);
cout << mm << endl;
MM result = mm++;
cout << mm << endl;
result = ++mm;
cout << mm << endl;
return 0;
}
文本重载 (新标准中的,稍微落后一点开发工具不适用)
其他运算符
- = () -> [] 只能采用类的成员函数形式重载, . .* ?: :: 不能重载
谢谢大家的阅读,新手上路,如有不足之处请及时指出,我好纠正,万分感激~