stl :: list中的C++接口

jac*_*kie 2 c++

LessonInterface

class ILesson
{
    public:
        virtual void PrintLessonName() = 0;
        virtual ~ILesson() {}
};
Run Code Online (Sandbox Code Playgroud)

stl容器

typedef list<ILesson> TLessonList;
Run Code Online (Sandbox Code Playgroud)

调用代码

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

错误:

描述资源路径位置类型将'const ILesson'作为'this'参数传递给'virtual void ILesson :: PrintLessonName()',丢弃限定符

Joh*_*ica 10

必须将PrintLessonName声明为const才能在const ILessons上调用.否则,编译器会假定它可能会修改ILesson并阻止调用.

virtual void PrintLessonName() const = 0;
Run Code Online (Sandbox Code Playgroud)


Ara*_*raK 7

您不能"放置"具有纯虚函数的类的对象(因为您无法实例化它).也许你的意思是:

// store a pointer which points to a child actually.
typedef list<ILesson*> TLessonList;
Run Code Online (Sandbox Code Playgroud)

好的,正如其他人指出的那样,你必须建立PrintLessonName一个const成员函数.我想补充一点,这里还有另一个小陷阱.PrintLessonName必须constbasederived类中,否则它们将具有相同的签名:

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() {}
};
Run Code Online (Sandbox Code Playgroud)

说实话,我发现Jerry Coffin的回答有助于重新设计打印功能.