C++ Interfaces in stl::list

2019-07-22 10:07发布

LessonInterface

class ILesson
{
    public:
        virtual void PrintLessonName() = 0;
        virtual ~ILesson() {}
};

stl container

typedef list<ILesson> TLessonList;

calling code

for (TLessonList::const_iterator i = lessons.begin(); i != lessons.end(); i++)
    {
        i->PrintLessonName();
    }

The error:

Description Resource Path Location Type passing ‘const ILesson’ as ‘this’ argument of ‘virtual void ILesson::PrintLessonName()’ discards qualifiers

标签: c++
8条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-22 10:53

Use iterator instead of const_iterator or make PrintLessonName() const function:

virtual void PrintLessonName() const = 0
查看更多
我命由我不由天
3楼-- · 2019-07-22 10:55

You can't "put" objects of a class that has pure virtual functions(because you can't instantiate it). Maybe you mean:

// store a pointer which points to a child actually.
typedef list<ILesson*> TLessonList;

OK, as others pointed out, you have to make PrintLessonName a const member function. I would add that there is another small pitfall here. PrintLessonName must be const in both the base and the derived classes, otherwise they will not have the same signature:

class ILesson
{
public:
    virtual void PrintLessonName() const = 0;
    virtual ~ILesson() {}
};


class SomeLesson : public ILesson
{
public:
    // const is mandatory in the child
    virtual void PrintLessonName() const
    {
        //
    }
    virtual ~SomeLesson() {}
};

To be honest, I find Jerry Coffin's answer helpful for redesigning the printing functionality.

查看更多
登录 后发表回答