2014-01-24 240 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

相關問題