2014-01-24 236 views
-1
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),它也不起作用。'std :: operator <<'operator <<'不匹配'std :: operator <<

-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用于打印星号,histo [count]提供要打印的星号数量。

COUT < < setprecision(3)< <我< < “到” < < 1 + 0.25 < < “:” < < printAst(HISTO [COUNT])< < ENDL;

+0

这与标题有什么关系? –

+3

'<< printAst(histo [count])'< - 这是错误的。这个函数返回void。你不能流无效。 – Borgleader

回答

0

您似乎对链接<<在流中的工作方式存在误解。

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; 
} 

你可以阅读更多关于operator overloading

相关问题