[英]How do I create an object with sub functions in C++?
我不擅长C ++,所以要准备好不恰当地使用术语。
基本上我想在另一个类的子类中收集一堆函数,所以我会像这样接口:
mainWindow.add.menubar();
^- this is the part I don't know how to do
我的班级目前看起来像这样:
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编程)会更好。
是的,我基本上是在创建自己的GUI框架而且C ++专业知识不足,我知道这是一个坏主意,但它并没有阻止我修改Linux内核以允许我在我的三星S4上安装Nethunter而且它不会现在停止我
您可以将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 :)
}
};
};
}
然后像使用它一样
Widow w;
w.add.menubar();
当然,你可以在这里做更多的样式(对于真实世界的代码):通过.h / .cpp文件从定义中单独声明,隐藏你不想用private公开的数据,声明Add添加为朋友类等。
要使它工作, add
必须是一个变量:
#include <string>
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();
};
Add add;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.