运算符&函数重载
重载决策
重载决策机制是C++中实现函数&运算符重载的重要依据:
重载函数
在类中,可以使用函数重载创造多个名称相同,功能相似的函数,根据传入参数的差异执行不同的功能。
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(string c) {
cout << "Printing character: " << c << endl;
}
};
重载运算符
使用关键字operator可以重载C++中的大部分内置运算符。
#include<iostream>
using namespace std;
class Box
{
private:
int length;
int width;
int height;
public:
Box(){}
Box(int a, int b, int c):length(a), width(b), height(c){}
Box(const Box& b)
{
this->length = b.length;
this->width = b.width;
this->height = b.height;
}
int getArea()
{
return this->width * this->length * this->height;
}
Box operator+(const Box &b);
};
Box Box::operator+(const Box &b)
{
Box box;
box.length = this->length + b.length;
box.width = this->width + b.width;
box.height = this->height + b.height;
return box;
}
int main()
{
Box a(1, 2, 3);
Box b(2, 3, 4);
cout << a.getArea() << endl;
cout << b.getArea() << endl;
Box c = a + b;
cout << c.getArea() << endl;
}
这样就重载了类的+运算符,使其可以将两个对象相加,得到一个新的对象。重写时使用引用不是必须的,但可以节省大量创建对象的时间。
上述调用重载运算符的方式称为隐式调用,若要显式的调用它们,可以按照下面的方式:
Box c = a.operator+(b);
不可重载的运算符:
:: | 范围解析运算符 |
.* 与 ->* | 成员指针访问运算符 |
sizeof | 长度运算符 |
?: | 条件运算符 |
# | 预处理符号 |
要注意,重载运算符需要注意一些规则:
-
只能重载C++语言中已有的运算符,不可臆造新的。
-
不能改变原运算符的优先级和结合性。
-
不能改变操作数个数。
-
不可声明为类属性。
-
要符合该运算符的使用习惯。
-
重载运算符函数的参数必须至少含有一个类类型操作数,不可以全是基本类型。
重载运算符不一定要定义为类的成员函数,也可以定义为友元函数、全局函数等。C++中就有实现运算符重载的大量实例,如:iostream 中的 cout 和 cin 使用的 << (流插入运算符)和 >>(流提取运算符)。