c++,简单函数,不合理错误



所以我有这样的代码:

#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
void printNumber(int x = 1, float z = 1.01);
int main(){
    int a = 54;
    float b = 39.1243;
    printNumber(a);
}
void printNumber(int x, float z){
    cout << x, z << endl;
}

因为我已经将float z的默认值设置为1.01,所以如果我不输入这两个参数,就不会出现错误。然而,它给了我这个错误:

错误:类型'float'和' to binary 'operator<<'无效的操作数

#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
void printNumber(int x = 1, float z = 1.01);
int main(){
    int a = 54;
    float b = 39.1243;
    printNumber(a);
}
void printNumber(int x, float z){
    cout << x << z << endl;
    cout << x << "," << z << endl; //alternative
}

change , to <<

CyberGuy已经(立即)提供了解决方案,我将添加一个关于操作符优先级和逗号操作符(具有最低优先级)在这里如何发挥作用的解释。

这是受影响的行:

cout << x, z << endl;

下一行是等价的,强调运算符优先级:

(cout << x), (z << endl);

如果您想进一步,您可以删除逗号操作符并拆分语句:

cout << x; // valid (although no flush)
z << endl; // invalid code

std::endl是一个流操纵符,实际上是一个函数,std::basic_ostream为它们定义了第9个成员operator<<重载。没有operator<<可以接受float

template<class CharT, class Traits>
std::basic_ostream<CharT, Traits> &endl(std::basic_ostream<CharT, Traits> &os);

- std::endl的声明