输出流中的函数调用优先级

Function call priority in output stream

所以,我有以下 class:

typedef double decimal;

class Ratio {
  int num, den;
  decimal val;

public:
  Ratio() { num = 1, den = 1, val = (decimal)num / den; }

  Ratio update(int a, int b) {
    num *= a, den *= b;
    val = (decimal)num / den;
    return *this;
  }

  decimal v(void) { return val; }

  friend ostream &operator<<(ostream &out, const Ratio &R) {
    return (out << R.num << ':' << R.den);
  }
};

当我在输出流中使用成员函数时:

cout<<"R = "<<R.update(2,1)<<"\tvalue = "<<R.v();

其中 R 是 Ratio 类型,首先调用右端的函数,因此它显示更新后的比率,但显示未更新的值:

R = 2:1    value = 1

我通过将流分成两部分克服了这个问题:

cout<<"R = "<<R.update(2,1), cout<<"\tvalue = "<<R.v();

所以我 "force" .update() 首先被调用。是否有另一种方法可以实现此目的,即仅使用一个流进行输出?

由于在 c++ 中没有保证的评估顺序,如果不将其拆分为单独的部分,它将无法工作,就像您在修复中所做的那样。

引用自cppreference

There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativity of operator+, but the function call to c may be evaluated first, last, or between a() or b() at run time

正如用户@super 指出的那样,从 c++17 开始,现在定义了移位运算符的求值顺序。它隐藏在我在上面链接的页面上的规则的第 19 条中。所以如果你会 c++17,你就完成了。

也将值放入 << 重载函数中,如

 friend ostream& operator<<(ostream &out,const Ratio &R){return (out<<"R = "<<R.num<<':'<<R.den<<"\tvalue = "<<R.val);}

现在

#include<iostream>

using namespace std;

typedef double decimal;

class Ratio{
    int num,den;
    decimal val;
public:
    Ratio(){num=1,den=1,val=(decimal)num/den;}
    Ratio update(int a,int b){
        num*=a,den*=b;
        val=(decimal)num/den;
        return *this;
    }
    friend ostream& operator<<(ostream &out,const Ratio &R){return (out<<"R = "<<R.num<<':'<<R.den<<"\tvalue = "<<R.val);}
};

int main()
{
    Ratio R;

    cout<<R.update(2,1)<<endl;

}

输出:

  R = 2:1 value = 2

  Process returned 0 (0x0)   execution time : 0.382 s
  Press any key to continue.