是否可以在一个对象中创建一个对象,该对象的构造函数是在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++ 是否      更新时间:2023-10-16

我正在学习用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对象的指针。