目录
3.文本重载:返回值类型和参数类型都是unsigned long long
1.什么是运算符重载?
赋予运算符具有操作自定义类型数据的功能
2.运算符重载的实质是什么?
实质:函数调用
3.运算符重载函数的写法
格式:函数返回值 函数名(参数){}
函数返回值:运算完成后的值决定
函数名:operator加上重载运算符组成函数名
参数:看运算符的操作数,具体参数个数要看你重载函数的形式
函数体:写运算符要实现的具体操作
友元函数重载运算符
类成员函数重载运算符
#include<iostream>
using namespace std;
class CT
{
public:
CT(int data) :data(data){}//构造函数
friend CT operator+(CT&one,CT&two);//友元函数重载:参数个数就是操作数
void print()
{
cout << data << endl;
}
bool operator>(CT object)//类成员函数重载:参数个数是操作数减一
{
if (this->data > object.data)
return true;
else
return false;
}
protected:
int data;
};
CT operator+(CT&one, CT&two){
return one.data + two.data;
}
int main(){
CT one(1) ,two(5),three(1);//创建两个对象
three = one + two;
three.print();
if (one > two)//两个对象是不支持直接比较的,所以这是我们可以对">"进行重载
{
cout << "one比较大!" << endl;
}
else
cout << "two比较大!" << endl;
while (1);
return 0;
}
特殊运算符重载
1. 流运算符重载
cin类型:istream类的对象
cout类型:ostream类的对象
流运算符:>> <<
2.++--运算符重载
#include<iostream>
#include<string>
using namespace std;
class L{
public:
L(string str,int age=0):str(str),age(age){}
L operator++(int)//++运算符重载,需要传入一个无用的参数用于标记
{
return L( str,age++);
}
friend ostream& operator<<(ostream&out,L& jack)//<<的重载
{
out<<jack.str << "\t"<<jack.age;
return out;
}
protected:
string str;
int age;
};
int main(){
L jack("jack",12);
jack++;
cout << jack << endl;
while (1);
return 0;
}
3.文本重载:返回值类型和参数类型都是unsigned long long
格式:unsigned long long operator""_(重载的对象)(unsigned long long) {}
对象隐式转换
#include<iostream>
#include<string>
using namespace std;
class link{
public:
link(string str, int age) :str(str), age(age){}
operator int()//隐式类型转换
{
return age;
}
protected:
string str;
int age;
};
int main(){
link G("张三",15);
int age = G;//一般情况下不允许直接将对象传给int类型的变量,此时就需要隐式类型转换
cout << age << endl;
while (1);
return 0;
}
重载综合案例
#include<iostream>
using namespace std;
class Array{
public:
Array(int data):data(data){
p = new int[data]{0};
}
int size(){
return data;
}
int& operator[](int index){
return p[index];
}
Array () = default;
~Array(){
delete[] p;
p = nullptr;
}
protected:
int data;
int *p;
};
int main(){
Array array(4);
for (int i = 0; i < array.size(); i++)
{
cin >> array[i];
}
for (int i = 0; i < array.size(); i++)
{
cout << array[i];
}
while (1);
return 0;
}