从封闭类继承的嵌套类

C/C++ - Nested Class Inheriting from Enclosing Class

本文关键字:嵌套 继承      更新时间:2023-10-16

我想使用嵌套类作为我正在构建的应用程序的一部分。我拥有的第一段代码(头文件,我为这个问题包含了一些代码)如下:

class Window {
public:
    indev::Thunk32<Window, void ( int, int, int, int, void* )> simpleCallbackThunk;
    Window() {
        simpleCallbackThunk.initializeThunk(this, &Window::mouseHandler); // May throw std::exception
    }
    ~Window();
    class WindowWithCropMaxSquare;
    class WindowWithCropSelection;
    class WindowWithoutCrop;
    virtual void mouseHandler( int event, int x, int y, int flags, void *param ) {
    printf("Father");
    }
private:
    void assignMouseHandler( CvMouseCallback mouseHandler );    
};
class Window::WindowWithCropMaxSquare : public Window {
public:
    WindowWithCropMaxSquare( char* name );
    virtual void mouseHandler( int event, int x, int y, int flags, void *param ) {
        printf("WWCMS");
    }
};
class Window::WindowWithCropSelection : public Window {
public:
    WindowWithCropSelection( char* name );
    virtual void mouseHandler( int event, int x, int y, int flags, void *param ) {
        printf("WWCS");
    }
};
class Window::WindowWithoutCrop : public Window {
public:
    WindowWithoutCrop( char* name );
    virtual void mouseHandler( int event, int x, int y, int flags, void *param ) {
        printf("WWOC");
    }
};

现在,我想在MAIN中实例化一个WindowWithCropMaxSquare类并执行mouseHandler函数。

在MAIN中有

Window::WindowWithCropMaxSquare *win = new Window::WindowWithCropMaxSquare("oopa");
win->mouseHandler(1,1,1,1,0);

但是,这会在链接阶段引起问题。我得到了以下错误:

错误1错误LNK2019:未解析的外部符号"public: __thiscall Window::WindowWithCropMaxSquare::WindowWithCropMaxSquare(char *)"(??0WindowWithCropMaxSquare@Window@@QAE@PAD@Z)在function _main中引用c:UsersNicolasdocumentsvisual studio 2010ProjectsAFRTProjectAFRTProjectAFRTProject.obj

那么,谁能告诉我如何解决这个问题?

您需要两样东西:每个构造函数的主体,以及正确的const'ness。

WindowWithCropMaxSquare( char* name );

只是一个没有任何定义(主体)的声明。空的构造函数主体,正如你在你的评论中暗示的,将是

WindowWithCropMaxSquare( char* name ) {}

我也很怀疑

Window::WindowWithCropMaxSquare *win = new Window::WindowWithCropMaxSquare("oopa");

需要一个接受const char*的构造函数,因为你给它一个常量(右值):

WindowWithCropMaxSquare( const char* name ) {}

WindowWithCropMaxSquare( const string& name ) {}

编译器不会给非const类型的函数提供常量作为实参,因为这样的函数表明它可能会修改给定的实参,显然不允许使用常量。