2016-06-30 3 views
-2

속성을 부여하고 난 FlowersGarden의 수는 종 내 목록에 장미 개체를 계산하려면 :계수 요소 그래서 나는이 두 개의 클래스를 가지고

class Garden { 
private: 
    string owner; 
    double lenght, width; 
public: 
    Garden(string ow, double l, double w) { 
     this->ownder = ow; 
     this->lenght = l; 
     this->width = w; 
} 

class FlowersGarden: public Garden { 
private: 
    string species; 
public: 
    FlowersGarden(string ow, double l, double w, string sp):Garden(ow, l, w) { 
     this->species = sp; 
} 
    string GetSpecies()const {return species;}; 
}; 

MAIN.CPP

Graden** list; 
list = new Garden* [5]; 
list[0] = new Garden("asdas", 54, 57); 
list[1] = new FlowersGarden("tyyty", 98, 87, "rose"); 
list[2] = new FlowersGarden("asdasd", 578, 212, "sadas"); 
list[3] = new Garden("uyiyui", 687, 212); 
int count = 0; 
for (int i = 0; i < 4; i++) 
    if(dynamic_cast<FlowersGarden*>(list[i])) 
     if(list[i]->GetSpecies() == "rose") 
      count++; 

그게 내가이 문제를 해결할 수 있다고 생각하는데 나는이 오류가 발생합니다. "class 'Garden'에는 'GetSpecies'라는 멤버가 없습니다. 이유는 알지만 다른 방법은 모르겠습니다.

+0

C에 대한 귀하의 사용 C#을 문법 ++는 것 같다. –

+0

대신에'GetSpecies()'GetSpecie()' – max66

+0

그건 오타 였지만 그게 문제의 원인이 아니 었습니다. – SuperChit

답변

0

if(dynamic_cast<FlowersGarden*>(list[i]))

이 가드는 파생 된 유형이 FlowerGarden 유형인지 제대로 검사합니다. 그러나 list[0]->GetSpecies은 여전히 ​​사용하려고하는 기능이없는 Garden 유형의 포인터를 사용하고 있습니다.

캐스트의 결과를 유지하고 함수를 호출하는 데 사용해야합니다.

if (FlowersGarden* result = dynamic_cast<FlowersGarden*>(list[i])) 
{ 
    if (result->GetSpecies() == "rose") 
    { 
     ... 
    } 
} 

참고 : 예를 들어 @ max66으로는 코멘트에 지적한다. 귀하가 게시 한 코드는 FlowersGarden 클래스의 기능에 대해 오타가있는 것으로 보입니다. GetSpecieGetSpecies입니다.


편집 :

나는 당신이 (당신의 클래스 계층 구조에 대한) 궁극적으로 뭘 하려는지 모르겠지만 나는 virtual 기능을 지적 때마침 것이다라고 생각했다. 모두 파생 된 클래스에 적용 할 수있는 함수가있는 경우에는 기본 클래스를 추가하여 virtual으로 만듭니다. 이렇게하면 dynamic_cast을 수행 할 필요가 없으며 기본 클래스 포인터를 통해 호출 될 때 동적 파생 클래스가 파생 클래스 구현을 호출합니다. 예를 들어

:

#include <iostream> 
#include <memory> 

class Base 
{ 
public: 
    virtual ~Base() {} 

    virtual void print() const = 0; // Pure abstract function 
}; 

class Derived : public Base 
{ 
public: 
    virtual void print() const override { std::cout << "Derived\n"; } 
}; 

int main() 
{ 
    std::unique_ptr<Base> base = std::make_unique<Derived>(); 
    base->print(); 

    return 0; 
} 

출력 :

Derived 

Live Example

관련 문제