简体   繁体   中英

Call multiple classes without if statements

This is just a quick question. I'm new to OOP. I want to make 2 classes named Level1 and Level2

class Level1{
  //some code
};
class Level2{
  //some code
};

In int main() I want to call first or second class depending on the input of the user.

int main(){
  int choice;
  cin>>choice;
}

Now the first option that comes to mind is to make 2 if statements, like this:

int main(){
  int choice;
  cin>>choice;
  if(choice == 1){
    Level1 level;
  }
  else if(choice == 2){
    Level2 level;
  }
}

But is there some way to just add the int that the user just entered next to "Level"? Like this:

int main(){
  int choice;
  cin>>choice;
  Level(choice) level;
  //the int choice should add 1 or 2 near the Level class
}

Sorry If I'm bad at explaning

You cannot, in C++, have functionality dependent on the name of something. C++ lacks reflection (by design). But there's various ways around it.

The OOP way would be:

#include <memory>
#include <iostream>

class Level
{
public:
    virtual void Load() {};
};

class Level1: public Level 
{
public:
    virtual void Load() {std::cout << "Level 1\n";};
};

class Level2: public Level 
{
public:
    virtual void Load() {std::cout << "Level 2\n";};
};


int main()
{
    std::shared_ptr<Level> levels[2] = {std::make_shared<Level1>(), std::make_shared<Level2>()}; 

    int i;
    std::cin >> i;

    if (i >= 0 && i < 2)
    {
        levels[i]->Load();
    }
}

It uses polymorphism so that you have an array of pointers to various specialized object. This is good when you have different behaviours.

Templates would offer a different way. std::functions and lambdas would be another way.

But if the behaviour is always the same, use a single class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM