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

标签 c++ c++11

我不是很擅长 C++,所以要为术语的不当使用做好准备。

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

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

我的类(class)现在看起来像这样:

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();
        };
    };
}

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

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

最佳答案

您可以将 Window* 指针注入(inject) struct 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 :)
            }
        };
    };
}

然后像这样使用它

Widow w; 
w.add.menubar();

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

关于c++ - 如何在 C++ 中创建具有子函数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48174245/

相关文章:

c++ - 可变参数模板无法识别 constexpr 函数

c++ - 如何避免两个不同头文件中的 typedef 冗余?

c++ - 隐藏函数的实例化

c++ - 作用域枚举的 "using namespace X"等效项?

c++ - Postgresql - 从 SELECT 中排除一些结果

c++ - 创建一个只有模板头文件的项目库文件

c++ - 我可以在其析构函数中使用指向已析构对象的指针吗?

c++ - 我是否正确使用 move 语义?会有什么好处?

c++ - 初始化一个类成员引用变量,就像它是一个常规变量一样

c++ - 在 clang 中声明一个非别名变量?