目录
一、基本介绍
不同于Java的禁止以及C#的部分运算符允许重载,C++给了我们更大的操作空间,是 C++ 语言的一个特性,允许程序员给已有的运算符赋予额外的含义,以适应不同数据类型的操作。这使得代码更加直观和易于理解,特别是在处理复杂的数据结构如类和对象时。
几乎所有的 C++ 内置运算符都可以被重载,除了 ::(域运算符)、.*(成员指针访问运算符)、sizeof(长度运算符)和三元条件运算符 ?:。
对于一个运算符,其本质上是一个函数,它具有一个特殊的名称(例如,对于加法运算符’+‘,函数名为' operator+')。
需要注意的是,重载运算符时应保持操作的直观性,不要违背运算符原本的含义。比如,+
运算符应该保持加法的直观含义。而且,重载运算符不会改变运算符的优先级。例如,即使重载了 + 和 *,* 仍然比 + 有更高的优先级。
由于运算符比较多,不可能全部的列出,而且有没有意义,因此下面只举例一些常见的使用.
二、使用实例
语法: 返回类型 opetator 运算符 (参数...)
1. 使用背景
#include<iostream>
struct Test
{
int x, y;
Test(int x,int y)
:x(x),y(y)
{}
Test Add(const Test& obj)const
{
return Test(x + obj.x, y + obj.y);
}
};
int main()
{
Test test1(1, 2);
Test test2(3, 4);
Test result = test1.Add(test2);
std::cout << result.x << " " << result.y << std::endl;
}
比如说创建了两个Test类进行测试,想要将其内容进行相加,如果在Java中那么解决办法就只有如上,但是在C++中可以使用运算符重载来是我们的代码更加的简洁。
2. 加乘重载
我们在结构体中对+运算符进行重载
#include<iostream>
struct Test
{
int x, y;
Test(int x,int y)
:x(x),y(y)
{}
Test Add(const Test& obj)const
{
return Test(x + obj.x, y + obj.y);
}
Test operator+ (const Test& obj) const
{
return Add(obj);
}
};
int main()
{
Test test1(1, 2);
Test test2(3, 4);
Test result = test1 + test2;
std::cout << result.x << " " << result.y << std::endl;
}
这样 test1 + test2 就比较直观好看了,此外还可以重载乘法,同时重载后运算的优先级是不会改变的。
#include<iostream>
struct Test
{
int x, y;
Test(int x,int y)
:x(x),y(y)
{}
Test Add(const Test& obj)const
{
return Test(x + obj.x, y + obj.y);
}
Test operator+ (const Test& obj) const
{
return Add(obj);
}
Test Mul(const Test& obj) const
{
return Test(x * obj.x, y * obj.y);
}
Test operator* (const Test& obj)const
{
return Mul(obj);
}
};
int main()
{
Test test1(1, 2);
Test test2(3, 4);
Test test3(5, 6);
Test result = test1 + test2;
std::cout << result.x << " " << result.y << std::endl;
result = test1 + test2 * test3;
std::cout << result.x << " " << result.y << std::endl;
}
3. 左移符重载
在输出的时候,发现需要对对象进行调用,比较麻烦。因此可以对“ << ”进行重载输入到cout流的数据,再打印到控制台上。
std::ostream& operator<< (std::ostream& stream, const Test& obj)
{
stream << obj.x << "," << obj.y;
return stream;
}
int main()
{
Test test1(1, 2);
Test test2(3, 4);
Test test3(5, 6);
Test result = test1 + test2;
std::cout << result.x << " " << result.y << std::endl;
result = test1 + test2 * test3;
std::cout << result.x << " " << result.y << std::endl;
std::cout << result << std::endl;
}