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

summaryReport()는 공극 함수이며, 저 오류 제공된다오버로딩 << 연산자 :: ostream에

no operator "<<" matches these operands

을했으나 오류가 I는 상기 summaryReport 기능을 변경하는 경우가없는 int,하지만 그 문제는 값을 반환해야하며 화면에 출력하는 것입니다.

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

void 함수를 사용하여 cout <<을 오버로드하는 방법이 있습니까?

답변

10

다음과 같이 당신은 summartReport가 매개 변수로 ostream&를 복용 정의해야합니다 :

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

다음으로 호출, "cout을 과부하"호출되지 않습니다 그런데

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

. 당신은 은 "std::ostream에 대한 operator<< 과부하, 말을해야

0

을 두 가지가 여기서 할 필요가있다 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);