uacs2024

导航

C++ 重载运算符和重载函数 二元运算符重载

C++ 允许在同一作用域中的某个函数运算符指定多个定义,分别称为函数重载运算符重载

重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但是它们的参数列表和定义(实现)不相同。

当您调用一个重载函数重载运算符时,编译器通过把您所使用的参数类型与定义中的参数类型进行比较,决定选用最合适的定义。选择最合适的重载函数或重载运算符的过程,称为重载决策

C++ 中的运算符重载

您可以重定义或重载大部分 C++ 内置的运算符。这样,您就能使用自定义类型的运算符。

重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。

Box operator+(const Box&);

声明加法运算符用于把两个 Box 对象相加,返回最终的 Box 对象。大多数的重载运算符可被定义为普通的非成员函数或者被定义为类成员函数。如果我们定义上面的函数为类的非成员函数,那么我们需要为每次操作传递两个参数,如下所示:

Box operator+(const Box&, const Box&);

下面的实例使用成员函数演示了运算符重载的概念。在这里,对象作为参数进行传递,对象的属性使用 this 运算符进行访问

 1 #include <iostream>
 2 using namespace std;
 3 class Box
 4 {
 5    public:
 6  
 7       double getVolume(void)
 8       {
 9          return length * breadth * height;
10       }
11       void setLength( double len )
12       {
13           length = len;
14       }
15  
16       void setBreadth( double bre )
17       {
18           breadth = bre;
19       }
20  
21       void setHeight( double hei )
22       {
23           height = hei;
24       }
25       // 重载 + 运算符,用于把两个 Box 对象相加
26       Box operator+(const Box& b)
27       {
28          Box box;
29          box.length = this->length + b.length;
30          box.breadth = this->breadth + b.breadth;
31          box.height = this->height + b.height;
32          return box;
33       }
34    private:
35       double length;      // 长度
36       double breadth;     // 宽度
37       double height;      // 高度
38 };
39 // 程序的主函数
40 int main( )
41 {
42    Box Box1;                // 声明 Box1,类型为 Box
43    Box Box2;                // 声明 Box2,类型为 Box
44    Box Box3;                // 声明 Box3,类型为 Box
45    double volume = 0.0;     // 把体积存储在该变量中
46  
47    // Box1 详述
48    Box1.setLength(6.0); 
49    Box1.setBreadth(7.0); 
50    Box1.setHeight(5.0);
51  
52    // Box2 详述
53    Box2.setLength(12.0); 
54    Box2.setBreadth(13.0); 
55    Box2.setHeight(10.0);
56  
57    // Box1 的体积
58    volume = Box1.getVolume();
59    cout << "Volume of Box1 : " << volume <<endl;
60  
61    // Box2 的体积
62    volume = Box2.getVolume();
63    cout << "Volume of Box2 : " << volume <<endl;
64  
65    // 把两个对象相加,得到 Box3
66    Box3 = Box1 + Box2;
67  
68    // Box3 的体积
69    volume = Box3.getVolume();
70    cout << "Volume of Box3 : " << volume <<endl;
71  
72    return 0;
73 }

结果

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

 

posted on 2024-03-02 20:45  ᶜʸᵃⁿ  阅读(6)  评论(0编辑  收藏  举报