我不是很擅长 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/