本质是Student s3=s1.operator+(s2);
class Student {
public:
int a;
int b;
Student operator+(Student& p) {
Student t;
t.a = this->a + p.a;
t.b = this->b + p.b;
}
};
本质调用:Student s3=operator+(s1,s2);
Student operator+(Student &s,Student &s1) {
Student t;
t.a =s.a + s1.a;
t.b = s.b + s1.b;
return t;
}
运算符重载也可以发生函数重载
Student operator+(Student &s,int s1) {
Student t;
t.a =s.a + s1;
t.b = s.b + s1;
return t;
}
不会利用成员函数重载<<运算符,因为无法实现cout在左侧
使用全局变量重载
如果想用类中的私有变量加友元:friend ostream& operator<<(ostream& cout, Student& s);
cout和out关键字属于输出流ostream
ostream& operator<<(ostream& cout, Student& s) {
cout << "a=" << s.a << "\tb=" << s.b;
//链式
return cout;
}
ostream& operator<<(ostream& out, Student& s) {
out << "a=" << s.a << "\tb=" << s.b;
//链式
return out;
}
void test() {
Student s1(10,20);
cout << s1 << endl;
}
class Student {
friend ostream& operator<<(ostream& cout, Student& s);
public:
int a;
int b;
Student() {
a = 0;
}
//重载前置++
Student& operator++() {
//先加
a++;
//再返回自身
return *this;
}
//后置++,int是占位参数,区分前置后后置
Student& operator++(int) {
//先记录结果
Student t = *this;
//后递增
a++;
//将记录返回
return t;
}
};
ostream& operator<<(ostream& out, Student& s) {
out << s.a ;
//链式
return out;
}
void test() {
Student s;
cout << ++(++s) << endl;
cout << s << endl;
}
void test1() {
Student s;
cout << s++ << endl;
cout << s << endl;
}
可以看看构造函数和析构函数深拷贝和浅拷贝:深拷贝和浅拷贝
class Student {
public:
int *a;
Student(int _a) {
a = new int(_a);
}
~Student() {
if (a != NULL) {
delete a;
a = NULL;
}
}
Student& operator=(Student& s) {
//编译器提供浅拷贝
//先判断是否有属性在堆区,如果有先释放干净,再深拷贝
if (a != NULL) {
delete a;
a = NULL;
}
a = new int(*s.a);
//返回对象本身
return *this;
}
};
void test() {
Student s(18);
Student s1(20);
Student s2(23);
cout << "年龄" << *s.a << endl;
s2 = s1=s;
cout << "年龄" << *s1.a << endl;
cout << "年龄" << *s2.a << endl;
}
bool operator!=(Student& s) {
if (this->a != s.a && this->b != s.b) {
return true;
}
return false;
}
1、函数调用运算符()也可以重载
2、由于重载后使用的方法非常像函数的调用,因此成为仿函数
3、仿函数没有固定写法,非常灵活
class Student {
public:
int a;
int b;
//打印输出函数重载
void operator()(string test) {
cout << test << endl;
}
//两个数相加
int operator()(int num1, int n2) {
return num1 + n2;
}
};
void test() {
Student s;
s("World");
cout << s(18, 20) << endl;
int ret = s(10, 10);
cout << ret << endl;
//匿名函数对象
cout << Student()(10, 10) << endl;
}