2012-02-20 5 views
4
class Product 
{ 
... 
} 

class Perishable : public : Product 
{ 
public: 
int getday(); 

} 


int main() 
{ 
    Product *temp; 
    //due to some coding 
    //temp could point to either Perishable object or Product object that is determine   //during runtime 
    cout<< ((Perishable*)temp)->getday() ;// is there other way to achieve this typecasting seems dangerous 

temp는 Product 객체에 temp를 지정하면 temp-> getday()가 유효하지 않으며이 문제를 방지하는 방법을 알지 못합니다. 어떤 상황으로 인해서, 나는 부양 할 수있는 제품에서만 getday()를 사용할 수 있지만, temp가 부패하기 쉬운 객체 또는 Product 객체를 가리키는 지 어떻게 확인할 수 있습니까?C++ 기본 다형성

어떤 도움을 주시면 감사하겠습니다/

}

+1

이것은 다형성의 목적을 무력화시키는 것 같습니다. 또는 귀하의 질문에 대한 오해입니다. – grep

+0

"다운 캐스트"에 대해 질문하는 것 같습니다. http://en.wikipedia.org/wiki/Downcast? – reuben

답변

3

을 "이 코드의 문제는 그 경우 제품을 임시 점 object, temp-> getday()는 유효하지 않을 것이고 나는 이것을 방지하는 방법을 모른다."

다른 답변에서 언급 한 것처럼 Product 클래스에서 getday()를 선언하거나 구현하고 싶지 않은 경우 동적 캐스트를 사용하여 변수의 런타임 유형을 결정할 수 있습니다

Product* pPerishable = new Perishable; 
    Product* pProduct = new Product; 
    Perishable * pActualPerishable; 

    pActualPerishable= dynamic_cast<Perishable *>(pPerishable); 
    //pActualPerishable will not be null because it is of type Perishable at run time 

    pActualPerishable = dynamic_cast<Perishable*>(pProduct); 
    //pActualPerishable will be null because you are trying to cast a runtime base type to a derived type. 

그래서, 동적 시도 부패하기 쉬운에 변수를 캐스팅, 성공은 당신이 알고있는 경우에 당신이 getday을 (호출 할 수 있습니다) 참고 이것이다 : 당신이 부패하기 쉬운 인스턴스가있는 경우, 다음 만 해당) (getday 호출합니다. 더 이상 다형성이 아니지만 런타임에 유형을 결정하면 작업중인 객체의 인터페이스를 제어 할 수없는 경우 특히 유용합니다.

+0

오, 그래서 dynamic_cast는 C#의 "as"키워드와 비슷합니까? 나는 전에 dynamic_cast를 사용한 적이 없으며 항상 유용하다는 것을 궁금해했습니다. –

+0

@Jonathan Henson 예, C#의 "as"키워드와 거의 동일하게 작동합니다. 나는 상속 구조를 멋지게 디자인한다면 아마도 많이 사용할 필요가 없을 것입니다. –

+0

감사합니다. 잘 작동합니다. – user1203499

0

getDayProduct 클래스의 virtual 기능이있는 경우, 당신은 캐스트가 필요하지 않습니다. 당신은 간단하게이를 작성할 수

cout<< temp->getday(); 

temp하면 포인트를 입력 Product의 객체에 다음 Product:getDay가 불려갑니다. tempPerishable 유형의 객체를 가리키는 경우 에서 오버라이드 된 경우 Perishable::getDay이 호출됩니다. 그렇지 않으면 Product::getDay이 호출됩니다.

이것이 런타임 다형성이 작동하는 방식입니다.

+0

OP가 여기에 타이 캐스팅을 요청할 것이라고 생각하지 않습니다. – Mahesh

0

다형성과 어떤 관계가 있습니까? getDay()도 Product에 정의되어 있다고 가정합니다. 그렇다면 상속과 다형성의 전체 목적입니다. 전화하실 수 있습니다

temp-> getday(); 캐스트에 대해 전혀 걱정할 필요가 없습니다. temp가 실제로 Product 또는 파생 상품 중 하나이고 getDate()가 Product에 가상으로 정의되어있는 한 어떤 캐스트도 필요하지 않습니다.

예 :

class Product 
{ 
public: 
    virtual int getday(); 
}; 

class Perishable: public Product 
{ 
public: 
    virtual int getday(); 
}; 

int main() 
{ 
    Product *temp; //= you should be getting the new from some factory method somewhere. 

    //Polymorphism will handle making sure that the right function is called here. 
    cout<< temp->getday(); 
} 
0

예를 들어 여러 가지 방법이 있습니다 다음의 메소드를 오버라이드 (override) 할

class Product 
{ 
    int getday() { return ... ; } // -1 for example or any invalid value 
} 

class Perishable : public : Product 
{ 
public: 
    int getday(); 
} 

또는

class Product 
{ 
    virtual int getday() = 0; 
} 

class Perishable : public : Product 
{ 
public: 
    virtual int getday(); // You must implement this somewhere 
} 
0

Polymorphicism 다음 가상 기본 방법을 필요로하며,이 하위 클래스 :

class Product 
{ 
    virtual int getday(); // You could also make this pure abstract 
} 

class Perishable : public Product 
{ 
public: 
int getday(); 
} 

class NonPerishable : public Product 
{ 
public: 
int getday(); 
} 


int main() 
{ 
    Product *temp; 
    temp = new Perishable();  
    cout << temp->getday(); // Perishable::getday() 

    temp = new NonPerishable();  
    cout << temp->getday(); // NonPerishable::getday() 

} 
2

내가 무엇을 당신이 필요로하는 것은이 생각 : 당신이 지금 할 수있는 이러한 변화와

class Product 
{ 
public: 
    virtual int getday() = 0; 
} 

class Perishable : public : Product 
{ 
public: 
    virtual int getday(); 
} 

:

cout << temp->getday(); 
0
class Product 
{ 
... 
} 

class Perishable : public : Product 
{ 
public: 
int getday(); 

} 


int main() 
{ 
    Product *temp; 
    //due to some coding 
    //temp could point to either Perishable object or Product object that is determine   //during runtime 

    Product *pObj = dynamic_cast<Perishable *>(temp); 
    if(!temp) 
    { 
     temp->getday(); //temp is containing Perishable Object. 
    } 
    else { 
     //it is Product Obj; 
    } 
} 

이 개념을 RTTI라고합니다. 개체 temp의 유형 이름을 찾으려면 typeid (temp) :: name()을 사용할 수도 있지만이 개체는 temp가 가리키는 개체 유형 만 반환합니다. typecasting을 수행하지 않습니다. dynamic_cast를 사용합니다.