运算符重载
class test{
public:
int a;
int b;
public:
test(int a=0, int b=0){
this->a=a;
this->b=b;
}
};
步骤一:定义全局函数
test add(test &t1, test &t2){
test tmp(t1.a+t2.a, t1.b+b2.b);
return tmp;
}
步骤二:对函数名进行改造
test operator+ (test &t1, test &t2){
test tmp(t1.a+t2.a, t1.b+b2.b);
return tmp;
}
int main(){
test t1(1, 2);
test t2(3, 4);
test t3=add(t1, t2); 普通全局函数
test t4=operator+(t1, t2); 步骤二用法
test t5=t1+t2; 利用步骤二的函数,可进行运算符重载
return 0;
}
运算符重载的本质是函数调用
不改变运算符的优先级,不改变运算符的结合性,不改变运算符的操作数个数,不能创建新的运算符
运算符重载的两种方法
1用成员函数或友元函数重载
运算符函数可以重载为友元函数和成员函数。
关键区别在于成员函数由this指针,友元函数没有
2用全局函数实现
对二元运算符进行重载
class test{
public:
int a;
int b;
public:
test(int a=0, int b=0){
this->a=a;
this->b=b;
}
public:
成员函数实现-重载
test operator-(test &t){
test tmp(this->a-t.a, this->b-t.b);
return tmp;
}
友元函数实现*重载
friend test operator*(test &t1, test &t2);
};
全局函数实现+重载
test operator+(test &t1, test &t2){
test tmp(t1.a+t2.a, t1.b+t2.b);
return tmp;
}
友元函数实现*重载
test operator*(test &t1, test &t2){
test tmp(t1.a*t2.a, t1.b*t2.b);
return tmp;
}
int main(){
test t1(1, 2);
test t2(3, 4);
test t3=t1+t2; 调用全局函数+重载
test t4=t1-t2; 调用成员函数-重载
}
友元函数对二元操作数重载时, 可以交换两个操作数的位置。
成员函数则不可以, 因为成员函数是相对于某一个对象来说的。
对一元运算符进行重载
class test{
public:
test(int a=0, int b=0){
this->a=a;
this->b=b;
}
成员函数实现重载前置--
test& operator--(){
this->a--;
this->b--;
return *this;
}
成员函数实现重载后置--
test& operator--(int){
test tmp=*this;
this->a--;
this->b--;
return tmp;
}
private:
int a;
int b;
友元函数实现重载前置++
friend test& operator++(test &t);
友元函数实现重载后置++
friend test& operator++(test &t, int);
};
test& operator++(test &t){
t.a++;
t.b++;
return t;
}
注意返回的不是引用
test operator++(test &t, int){
test tmp=t;
t.a++;
t.b++;
return tmp;
}
int main(){
test t1(1, 2), t2(3, 4);
++t1; 友元函数实现重载前置++
--t1; 成员函数实现重载前置--
t1++; 友元函数实现重载后置++
t2--; 成员函数实现重载后置--
}
重载=操作符
1 释放旧的内存
2 返回一个引用
3 根据大小分配内存
4 赋值
class test{
public:
test(const char *var_p){
len=strlen(var_p);
p=(char *)malloc(sizeof(len+1));
strcpy(p, var_p);
}
test& operator=(test &obj){
if (this->p!=NULL){
delete []p;
len=0;
}
this->len=obj.len;
this->p=new char[len+1];
strcpy(p, obj.p);
return *this;
}
~test(){
if (p!=NULL){
delete []p;
p=NULL;
len=0;
}
}
private:
int len;
char *p;
};
int main(){
test t1("abcde");
test t2("12345");
t1=t2;
}
函数模板
#include <iostream>
using namespace std;
template <typename T>
T get_max(T a, T b){
T ans =a>b?a:b;
return ans;
}
int main(){
double c=1.0, d=2.1;
double max_double=get_max<double>(c, d);
cout<<max_double;
return 0;
}
类模板和函数模板一样,在类的前面添加template <typename T>
在类的内部把数据类型该换成T, 使用时用class<T> name即可