如何在C++中创建具有子函数的对象?

Sim*_*yll 2 c++ c++11

我不擅长C++,所以要准备好不恰当地使用术语.

基本上我想在另一个类的子类中收集一堆函数,所以我会像这样接口:

mainWindow.add.menubar();
            ^- this is the part I don't know how to do
Run Code Online (Sandbox Code Playgroud)

我的班级目前看起来像这样:

namespace GUI {
    class Window {
    public:
        std::string title = "Empty Title";
        int show();
        // Using a struct didn't work but it's what I have at the moment.
        struct add {
            int menubar();
        };
    };
}
Run Code Online (Sandbox Code Playgroud)

显然我可以简单地使用,mainWindow.addMenubar()但将它添加到子类(子对象?我不知道,我更习惯于Javascript编程)会更好.

是的,我基本上是在创建自己的GUI框架而且C++专业知识不足,我知道这是一个坏主意,但它并没有阻止我修改Linux内核以允许我在我的三星S4上安装Nethunter而且它不会现在停止我

StP*_*ere 5

您可以将Window*指针注入结构Add()构造函数,例如:

namespace GUI {
    class Window {
    public:
        std::string title = "Empty Title";
        Add add;     // <- NOTICE: this is an instance of struct Add
                     // which holds the pointer to the window you want 
                     // to draw on
    public:
        Window() : add{this} {}
        int show();
        // Using a struct didn't work but it's what I have at the moment.
        struct Add {
            Window* win;
            Add(Window* w) : win{w} {}
            int menubar() {
                //  here you can use win to draw the puppy :)
            }
        };
    };
}
Run Code Online (Sandbox Code Playgroud)

然后像使用它一样

Widow w; 
w.add.menubar();
Run Code Online (Sandbox Code Playgroud)

当然,你可以在这里做更多的样式(对于真实世界的代码):通过.h / .cpp文件从定义中单独声明,隐藏你不想用private公开的数据,声明添加为朋友类等.