2014-10-01 2 views
-1

참조로 추상 클래스의 객체를 전달하려고 시도했지만이 객체를 동일한 데이터 유형의 포인터 배열에 저장하려고하면 분명히 오류가 발생합니다. 아무도 내가 뭘 잘못 설명 할 수 있을까요? 은 다음과 같은 기능에있어 : ​​배열에 추상 객체를 저장하는 C++

void enterItem(DessertItem& item) 
    { 
     if (top != (maxSize-1)) 
     { 
      arr[top] = &item; 
      top++; 
     } 
    } 

dessertItem 클래스는 실제로는 추상 클래스이며, 그것을 참조로 전달되는 때마다 새로운 개체에 대한 참조를 제공 할 수 있도록 "편곡"dessertItem의 포인터 배열입니다. 나는 그것을 어떻게 해야하는지 알 수 없다.

class Checkout 

    { 

     ////Maintains a list of DessertItem references. 
     protected: 

     int maxSize; 

     int top; 

     DessertItem **arr; 


    public: 

    Checkout() 

    { 

    ///Creates a Checkout instance with an empty list of DessertItem's 


     this->maxSize=5; 
     this->top=0; 
     this->arr = new DessertItem*[maxSize]; 
     for(int i=0; i<maxSize; i++) 
     { 
      arr[i]=NULL; 
     } 
    } 


    ////Clears the Checkout to begin checking out a new set of items 
    void clear() 

    { 

     for(int i=0; i<maxSize; i++) 
     { 
      arr[i]=NULL; 
     } 
    } 


    //A DessertItem is added to the end of the list of items 

    void enterItem(DessertItem &item) 

    { 

     if(top!=(maxSize-1)) 


     { 
      arr[top]=&item; 
      top++; 
     } 
    } 


    //Returns the number of DessertItem's in the list 


    int numberOfItems() 

    { 

     return this->top; 
    } 

    }; 
+0

이 우리에게 당신이 표시되는 오류 메시지를 보여주십시오. – jweyrich

+0

예상되는 타입 지정자입니다. 실제로 그게 무슨 뜻 이죠? –

+0

여기서는 arr이고 상단은 정의 되었습니까? –

답변

1

저장 vector<unique_ptr<T>>에 추상 개체 : 다음은 클래스입니다.

class Base { 
public: 
    virtual ~Base() = default; 
    virtual void method() = 0; 
}; 

class Impl : public Base { 
public: 
    void method() override { /* perform action here */ }; 
}; 

생성 및 저장과 같이 : 당신이 그들을 구성 할 때, 예를 들어, unique_ptr로를 구성

// nasty old c-style array 
std::unique_ptr<Base> a[10]; 
a[0] = std::move(std::unique_ptr<Base>(new Impl)); 

// std::vector 
std::unique_ptr<Base> p { new Impl }; 
std::vector<std::unique_ptr<Base>> v; 

v.push_back(std::move(p)); 
// or 
v.emplace_back(new Impl); 
+0

나는 벡터와 함께 일 해본 적이 없다. 아직 초보자 다. 벡터를 사용하지 않고 정렬 할 수있는 방법이 있습니까? –

+0

unique_ptr의 C 스타일 배열의 사용법을 보여주기 위해 업데이트 된 답변

+2

@Brainy_ std :: vector와 같은 C++ 클래스에 대한 가장 중요한 규칙은 지저분한 오래된 C 스타일 배열보다 엉망이되는 것입니다. 당신이 배우고 있기 때문에 피할 이유가 절대적으로 없습니다. – o11c

관련 문제