将任何对象传递给函数以创建该对象

问题描述 投票:1回答:1

我正在使用openframeworks和c ++制作小型的生成视频分层软件。为此,我有一个主类,一个图层类和许多不同类型的视频/模拟类。我需要这样做,以便当我按下一个键时,会加载不同的模拟。

我有两个问题:

  1. 如何访问所有模拟类的列表?
  2. 接下来,我如何将这个列表中的一个选择提供给可以接受任何类型的对象并启动它的函数?

我绘制了一个图,而不是使用代码对括号进行编码,以使所有3个块都在同一水平线上(实际代码在下面)。>>

enter image description here

为清楚起见,这是代码中的main.cpp和layer.cpp:

// main.cpp
void ofApp::setup(){
    layer1.setup();
    layer2.setup();
    layer3.setup();
}

void ofApp::update(){
    layer1.update(); 
    layer2.update(); 
    layer3.update(); 
}

void ofApp::draw(){
    layer1.draw(); 
    layer2.draw(); 
    layer3.draw(); 
}

void ofApp::keyPressed(int key){
    switch (key)
    {
    case '1':
        // get first class from list of classes
        layer1.changeSim(); // input first class from list of simulation classes
        break;
    default:
        break;
    }
}

和layer.cpp

void layer::setup(){
simulation = new Simulation();  // how do i initialize the Simulation variable if I dont know what type itll be ?
}

void layer::update(){
    simulation.update(); 
}

void layer::draw(){
    simulation.draw(); 
}

void layer::changeSim(){
    simulation = new Simulation(); // destroy old simulation and create new one, but will be of a different class
}

我正在使用openframeworks和c ++制作小型的生成视频分层软件。为此,我有一个主类,一个图层类和许多不同类型的视频/模拟类。我...

c++ oop openframeworks
1个回答
0
投票

最佳方法是使用称为工厂模式的东西。

© www.soinside.com 2019 - 2024. All rights reserved.