1、加号运算符重载
通过在类中,或者全局,来实现 加号的重载。
class Person{
public:
int A;
int B;
//1、通过成员函数重载 + 号
Person operator+(Person &p){
Person temp;
temp.A = this.A + p.A;
temp.B = this.B + p.B;
return temp;
}
};
//2、通过全局函数重载+号
Person operator+(Person &p1, Person &p2){
Person temp;
temp.A = p1.A + p2.A;
temp.B = p1.B + p2.B;
return temp;
}
void test01(){
Person p1;
p1.A = 10;
p1.B = 10;
Person p2;
p2.A = 10;
p2.B = 10;
Person p3 = p1 + p2;//两种方法都能重载定义+号
//成员函数重载的本质上是:
//Person p3 = p1.operator+(p2);
//全局函数重载的本质上是:
//Person p3 = operator+(p1, p2);
}
2、左移运算符重载
重载 左移运算符 可以实现输出 自定义数据类型
class Person{
friend ostream& operator<<(ostream &out, Person &p);
//全局函数友元声明
//1、利用成员函数重载 "<<" 的效果是:p.operator<<(cout) ,简化为:p<<cout
//此时的 cout 只能放在右边,无法实现cout在左侧
private:
int A;
int B;
}
//只能使用全局函数来重载<<
ostream& operator<<(ostream &out, Person &p){
out << p.A << p.B;
return out;
}
因为是全局变量,而类中的属性是私有的,所以,必须friend声明一下,才能访问。
3、重载 = 运算符
为了实现对象间的拷贝,实际上可以直接用 = 将两个对象写起来:p2 = p1
,便是将 p1 的内容全部拷贝给 p2 ,也就是说编译器会自动帮我们重载 =运算符,但是编译器自定义的是浅拷贝,可以自己写个深拷贝。
class Person{
public:
Person(){
Age = new int(age); //在初始化的时候,把创建的变量Age放在堆区
}
Person& operator=(const Person &p){ //更加科学的做法是加入const防止更改
if(Age != NULL){ //如果这个将要被覆盖的Age指针有值,我们就先删除它
delete Age;
Age =NULL;
}
Age = new int(*p.Age);//为了实现深拷贝,复制的时候,自己需要开辟一块内存
}
private:
~Person(){ //自己新建的内存记得自己手动释放
if(Age != NULL){
delete Age;
Age = NULL;
}
}
int* Age;
}
4、重载()运算符
这玩意儿可以重载了来写 仿函数 。仿函数的写法非常灵活。
class MyAdd{
public:
int operator()(int num1, int num2){
return num1 + num2;
}
};
void test01(){
MyAdd myadd;
int sum = myadd(100, 100);
//使用方法非常像一个真的函数,实际上是重载了()。
cout << Myadd()(100, 100) << endl;
/*也可以使用一个 匿名函数对象,即使用 类名() 这样的方式,
建立一个匿名对象,用完就删除*/
}
5、重载==运算符
class Person{
public:
int age;
bool operator==(Person& p){
if(this->age == p.age)return true;
return false;
}
}
==运算符返回的是一个 bool 类型的变量。
6、类外重载*运算符
class CVector{
int x;
int y;
};
inline CVector operator*(float num,const CVector& v){
return CVector(v.x * num, v.y * num);
}
若果想要把标准类型写在前面,自定义的类写在后面,必须在类外定义这个方法。
7、重载++(前置++和后置++)
//前置++的重载没有参数
Test& operator ++ ()
{
cout << "前置++" << endl;
++x;
++y;
return *this;
}
//后置++有一个int参数 但是可以不使用
Test operator ++ (int)
{
cout << "后置++" << endl;
Test temp = *this;
++x;
++y;
return temp;
}
8、强制类型转换重载
通过这样的方式把其他的类型强行转换成自己的定义的类型
operator int() { return color32; }
将 int 转换成自己的值。