是否可以在一个对象中创建一个对象,该对象的构造函数是在c++中创建它的对象
Is it possible to create an object in an object which has as constructor the object from which it was created in c++
我正在学习用c++构建程序,但一直停留在一些基本的东西上。我使用SDL2从屏幕获取输入并处理屏幕等。我定义了一个对象"Program"和一个对象"EventHandler"。"事件处理程序"处理所有事件(将事件发送到较低级别的对象),但"事件处理"也应该能够创建一个新窗口,从而访问"程序"。
这意味着我猜测"EventHandler"应该与"Program"处于同一级别,并且它们都应该能够相互通信。这可以在c++中实现吗?如何实现?也许还有其他更合乎逻辑的方法。
下面的代码显然不起作用,因为类的定义顺序,我自己制作的发送"程序"地址的"&this"是错误的,但它很好地概述了我正在尝试做什么。
//handles all events, is in contact with and same level as Program
class EventHandler {
private:
Program *program = NULL;
SDL_Event e;
//inputarrays
const Uint8 *currentKeyStates;
int mouseX = 0;
int mouseY = 0;
bool mousemotion = false;
int mouseButtons[4] = {0, 0, 0, 0};
public:
EventHandler(Program *p) {
program = p;
}
void handleEvents() {
while(SDL_PollEvent(&e) != 0) {
}
}
};
class Program {
private:
EventHandler *eh = NULL;
std::vector<Window> windows;
public:
bool running;
Program() {
//Here the most basic form of the program is written
//For this program we will use SDL2
//Initialize SDL
SDL_Init(SDL_INIT_EVERYTHING);
//This program uses 1 window
Window window(200, 200, 1200, 1000, "");
windows.push_back(window);
//Adds an event handler
eh = new EventHandler(&this);
//now simply run the program
run();
}
void run() {
running = true;
//while (running) {
//}
SDL_Delay(2000);
delete eh;
//Quit SDL subsystems
SDL_Quit();
}
};
int main( int argc, char* args[]) {
Program program;
return 0;
}
是的,这是可能的,而且你很接近
this
已经是一个指针。它已经是"Program
的地址"
当您编写&test
时,您获得的是指向某个指针的指针,而这不是您想要的。
所以你只需要写:
new EventHandler(this);
现在我并不是说这种紧密耦合是个好主意,但我承认我过去也做过类似的事情,它可以在可接受的程度上发挥作用。
如果您从Program
中获取想要共享的任何资源,并在两个类之间进行共享,那么您的设计将更加清晰明了。
您需要的是Program
的前向声明
class Program;
class EventHandler
{
private:
Program *program;
....
};
class Program
{
....
};
这样的声明允许您在完全定义类型之前声明指向Program
对象的指针。
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象