문제

I'm learning C++ and in a school assignment I must use a diamond structure even if it is not totally correct.

class Book
{
    public:
        virtual int getPurchasePrice() const;
    protected:
        int m_purchasePrice;
};
class AdultBook: virtual public Book{} ;
class ChildrenBook: virtual public Book{} ;
class ComicBook: public AdultBook, public ChildrenBook {} ;

(I removed every methods and constructors to simplify)

Now, if I want to create a ComicBook and to know its purchasePrice, how can I do ? If I do getPurchasePrice() on a ComicBook I get the following error:

error: request for member 'getPurchasePrice' is ambiguous

I thought that putting virtual for ChildrenBook and AdultBook would solve the ambiguity ?

도움이 되었습니까?

해결책

You use either

obj->AdultBook::getPurchasePrice();

or

obj->ChildrenBook::getPurchasePrice();

or

obj->Book::getPurchasePrice();

For obj of type ComicBook

EDIT FOR Emilio Garavaglia

Lets assume that you have not redefined getPurchasePrice for adult and childrens book, you could have this

Key A - Adult book, C - Childrens book, CB - Comic Book, B - Book

enter image description here

다른 팁

This is most likely due to the fact that getPurchasePrice is implemented in both AdultBook and ChildrenBook, but not in ComicBook, that inherits two different implementations for a same virtual function.

You have to override getPurchasePrice for ComicBook as well, and eventually implement with a call to one of the two bases's.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top