2011-12-08 2 views
14

이것은 큰 과제의 작은 부분이므로이 구문에 대한 확신이 없습니다.C++, 파생 클래스에서 기본 클래스의 오버로드 된 추출 연산자를 호출하려면 어떻게해야합니까?

나는이 회원이 Vehicle라는 기본 클래스가 있습니다 int fuelAmtint fuelUsage)

(내가 사용을 네임 스페이스 std)

내가 << 운영자 이런 식으로 오버로드 :

ostream& operator<<(ostream& osObject, const Vehicle& myVehicle) 
{ 
    cout << "Fuel Usage Rate: " << myVehicle.fuelUsage << endl 
     << "Fuel Amount:  " << myVehicle.fuelAmt << endl; 

    return osObject; 
} 

다음과 같이 호출합니다.

,515,
cout << Vehicle; 

결과 (예)이다

Fuel Usage Rate: 10; 
Fuel Amount: 50; 

I는 또한 클래스에서 파생 VehicleAirplane 클래스가, 그 새로운 멤버를 소개한다 int numEngines. 처음은 "차량 오버로드 된 연산자의 결과를"호출 한 후 어떤 결과가 내가 파생 된 클래스에서 인쇄 할 << 연산자를 말할 수 있도록

가 나는 Airplane 클래스의 << 연산자를 오버로드 할 수있는 방법 ... 그래서, 여기 내 말은 무엇을 :

나는 그것이 Airplane 클래스에서이 같은 기능을해야합니다

ostream& operator<<(ostream& osObject, const Airplane& myAirplane) 
{ 
     //First print the Fuel Usage rate and Fuel amount by calling 
     //the Base class overloaded << function 

     //then 
     cout << "Number of Engines: " << myAirplane.numEngines << endl; 

    return osObject; 
} 

어떻게이 파생 클래스에서, 그 회원들의 값을 출력하는 기본 클래스의 실행을 유발 하는가?

헤더를 변경하는 것과 비슷합니까? 이처럼 다음에 대한

ostream& operator<<(ostream& osObject, const Airplane& myAirplane): operator<<Vehicle 
+1

연산자 <<을위한 차량을 작동에만 기본 클래스 및 가상 파견 운영자 < <을 가지고, 최종적으로

class Base { public: virtual std::ostream& output(std::ostream& out) const { return out << "Base"; } virtual ~Base() {} //Let's not forget to have destructor virtual }; class Derived : public Base { public: virtual std::ostream& output(std::ostream& out) const { Base::output(out); //<------------------------ return out << "DerivedPart"; } virtual ~Derived() {} //Let's not forget to have destructor virtual }; 

하고 다음을 수행 코우트. osObject에 써야합니다. – user763305

답변

16

방법 :

ostream& operator<<(ostream& osObject, const Airplane& myAirplane) 
{ 
    osObject << static_cast<const Vehicle &>(myAirplane); 
    osObject << "Number of Engines: " << myAirplane.numEngines << endl; 

    return osObject; 
} 
+0

당신은'const vehicle '에 캐스팅해야합니다. –

+0

@ArmenTsirunyan : 제안에 따라 대답이 업데이트되었습니다. –

+0

'* static_cast (this)'의'this'를'& myAirplane'로 바꾸면 안됩니까? 마찬가지로'Airplane.numEngines' 대신'myAirplane.numEngines'을 사용합니까? – yasouser

16

운영자 < < 비회원 기능이기 때문에, 당신은 당신이 원하는 이상적 무엇 인 가상을 선언 할 수 없습니다. 그래서 당신은 당신이 쓸 마법

std::ostream& operator << (std::ostream& out, const Base& b) 
{ 
    return b.output(out); 
} 
1
ostream& operator<<(ostream& osObject, const Airplane& myAirplane) 
{ 
    //First print the Fuel Usage rate and Fuel amount by calling 
    //the Base class overloaded << function 
    cout << (Vehicle&) myAirplane; 

    //then 
    cout << "Number of Engines: " << myAirplane.numEngines << endl; 

    return osObject; 
} 
관련 문제