与"std::运算符"中的'operator <<'不匹配<<

no match for 'operator <<' in 'std::operator<<

本文关键字:lt 不匹配 operator 中的 std 运算符      更新时间:2023-10-16
void printAst(int x)
{
    for( int i = 0; i < x; i++)
    {
        cout << "*";
    }
    cout << " (" << x << ")" << endl;
}
void printHisto(int histo[])
{
    //cout.precision(3);
    int count = 0;
    for(double i = -3.00; i < 3.00; i += 0.25)
    {
        cout << setprecision(3) << i << " to " << i + 0.25 << ": " << printAst(histo[count]) << endl;
        // cout << setw(3) << setfill('0') << i << " to " << i + 0.25 << ": " << histo[count] << endl;
        count ++;
    }
}

我希望我的输出像这样进行格式化,所以我使用了setPrecision(3),也不起作用。

-3.00至-2.75:(0)
-2.75至-2.50: *(1)
-2.50至-2.25: *(1)
-2.25至-2.00:*(6)
-2.00至-1.75: ** * ** (12)

因此,它像这样的格式化

-3至-2.75:3
-2.75至-2.5:4
-2.5至-2.25:5
-2.25至-2:0
-2至-1.75:0

然而,主要问题是,当我尝试将printast称为Histo [Count]时。这就是导致此错误的原因。printast用于打印asteriks,Histo [Count]提供了要打印的asteriks的量。

cout&lt;&lt;setPrecision(3)&lt;&lt;i&lt;&lt;" to"&lt;&lt;i 0.25&lt;&lt;":"&lt;&lt;printast(histo [count])&lt;&lt;endl;

您似乎对<<如何在流中工作有误解。

cout << 42看起来像一个具有两个操作数的操作员表达式,但这确实是对具有两个参数的函数的调用(函数的名称为 operator<<)。此功能返回对流的引用,该流可以链接。

这样的表达:

cout << 1 << 2;

等效于此:

operator<<( operator<<(cout, 1), 2);

现在,问题在于,函数的参数不能为void,但这就是printAst返回的。取而代之的是,您需要返回可以流的东西 - 换句话说,operator<<已经超载的东西。我建议std::string

std::string printAst(int x);
{
    std::string s = " (" + std::string(x,'*') + ")";
    return s;
}

您可以阅读有关操作员过载的更多信息。