2012-04-24 12 views
2
ostream& operator <<(ostream& osObject, const storageRentals& rentals) 
{ 
    osObject << rentals.summaryReport(); 
    return osObject; 
} 

summaryReport()はvoid関数であり、それは私にエラーを与えている:は、<<のstd演算子のオーバーロード:: ostreamに

no operator "<<" matches these operands

が、私はANにsummaryReport機能を変更した場合、エラーはありませんintしかし、私が持っている問題は、値を返さなければならず、画面上にそれを印刷しているということです。

void storageRentals::summaryReport() const 
{ 
    for (int count = 0; count < 8; count++) 
     cout << "Unit: " << count + 1 << " " << stoUnits[count] << endl; 
} 

cout <<にvoid機能をオーバーロードする方法はありますか?

答えて

10

次に示すように、パラメータとしてostream&を取っsummartReportを定義する必要があります。

std::ostream& storageRentals::summaryReport(std::ostream & out) const 
{ 
    //use out instead of cout 
    for (int count = 0; count < 8; count++) 
     out << "Unit: " << count + 1 << " " << stoUnits[count] << endl; 

    return out; //return so that op<< can be just one line! 
} 

を、次にとしてそれを呼び出す:ところで

ostream& operator <<(ostream& osObject, const storageRentals& rentals) 
{ 
    return rentals.summaryReport(osObject); //just one line! 
} 

、それは "裁判所未満の過負荷を" と呼ばれていません。あなたはstd::ostreamためoperator<<をオーバーロード」、言うべき

0

あなたがここで行う必要がある2つのものがありますstorageRentals::summaryReport()std::ostream&std::coutにすることができますデフォルトこれを)取る行います。

void storageRentals::summaryReport(std::ostream& os) const 
{ 
    for (int count = 0; count < 8; count++) 
    { 
     os << "Unit: " << count + 1 << " " << stoUnits[count] << endl; 
    } 
} 

その後したがって、それを呼び出す:

ostream& operator <<(ostream& osObject, const storageRentals& rentals) 
{ 
    rentals.summaryReport(osObject); 
    return osObject; 
} 

注:storageRentals::summaryReport()std::ostream&とする利点は、ユニットテストでstd::ostringstreamを渡して、正しい出力を提供していると主張することです。

0

coutをオーバーロードすると、codeを使用して他の場所を分かりにくくしたり、混乱を招くことがあります。実際に、自分のクラスを作って作業を完了することができます。例えばクラスclass MyPringを作成し、オーバーロードのoperator <<をオーバーロードします。

0

ストレージレポートは、常に暗黙的に常にcoutにストリームされます。 あなたの関数をこのように呼び出して、ファイルの代わりにcoutにレンタルしている人がいるとします。

fstream fs("out.txt"); 
storageRentals rentals; 
fs << rentals; 

なぜ、このようなあなたのクラスはストリーミングされません。

ostream& operator <<(ostream& osObject, const storageRentals& rentals) 
{ 

    for (int count = 0; count < 8; count++) { 
     osObject << "Unit: " << count + 1 << " " << rentals.stoUnits[count] << endl; 
    } 
    return osObject; 
} 

をstoUnitsメンバーがプライベートである場合は、ストリーム機能ストレージクラスの友人を作成する必要があります。

friend ostream& operator<<(ostream& osObject, const storageRentals& rentals);