c++算术运算符重载时外部传入参数的位置

在使用运算符重载时,突然想知道声明中函数的参数是表达式的哪一个消息:

#include <iostream>
using namespace std;
//普通运算符重载
// 声明加法运算符用于把两个 Box 对象相加,返回最终的 Box 对象。
// 大多数的重载运算符可被定义为普通的非成员函数或者被定义为类成员函数。
// 定义为类成员函数:Box operator+(const Box& b){...}
// 定义为类的非成员函数:Box operator+(const Box& a,const Box& b){...}

class Box
{
   public:
 
      double getVolume(void)
      {
         return length * width * height;
      }
      void setLength( double len )
      {
          length = len;
      }
 
      void setWidth( double bre )
      {
          width = bre;
      }
 
      void setHeight( double hei )
      {
          height = hei;
      }
      // 重载 + 运算符,用于把两个 Box 对象相加
      // 参数表示+运算符右侧的对象。
      // this指针指向左侧的对象    
      Box operator+(const Box& b)
      {
         Box box;
         box.length = this->length + b.length;
         cout << "this->length: " << this->length <<endl;
         cout << "b.length: " << b.length <<endl;

         box.width = this->width + b.width;
         box.height = this->height + b.height;
         return box;
      }

   private:
      double length;      // 长度
      double width;     // 宽度
      double height;      // 高度
};
// 程序的主函数
int main( )
{
   Box Box1;                // 声明 Box1,类型为 Box
   Box Box2;                // 声明 Box2,类型为 Box
   Box Box3;                // 声明 Box3,类型为 Box
   double volume = 0.0;     // 把体积存储在该变量中
 
   // Box1 详述
   Box1.setLength(6.0); 
   Box1.setWidth(7.0); 
   Box1.setHeight(5.0);
 
   // Box2 详述
   Box2.setLength(12.0); 
   Box2.setWidth(13.0); 
   Box2.setHeight(10.0);
 
   // Box1 的体积
   volume = Box1.getVolume();
   cout << "Volume of Box1 : " << volume <<endl;
 
   // Box2 的体积
   volume = Box2.getVolume();
   cout << "Volume of Box2 : " << volume <<endl;
 

   // 把两个对象相加,得到 Box3
   Box3 = Box1 + Box2;
 
   // Box3 的体积
   volume = Box3.getVolume();
   cout << "Volume of Box3 : " << volume <<endl;
 
   return 0;
}

  打印结果为:

Volume of Box1 : 210
Volume of Box2 : 1560
this->length: 6
b.length: 12
Volume of Box3 : 5400

通过函数参数表是的是运算符右侧的对象。

原文链接: https://www.cnblogs.com/KeepThreeMunites/p/11351803.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++算术运算符重载时外部传入参数的位置

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/300923

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午9:49
下一篇 2023年2月15日 下午9:49

相关推荐