zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    常用不等式例题整理
    洛谷P1233 木棍加工题解 LIS
    莫比乌斯反演
    CSS样式使用
    相邻元素的层级(仿淘宝页面效果)
    js基础知识梳理(最简版)
    css2基础知识梳理
    html4基础知识梳理
    mysql密码遗忘和登陆报错问题
    mysql修改密码过期时间以及密码复杂性问题
  • 原文地址:https://www.cnblogs.com/KeepThreeMunites/p/11351803.html
Copyright © 2011-2022 走看看