Declare local classes as public

Asked

Viewed 56 times

1

Hello, I have a problem that blow my head off:

I’m making a script in C++ with the goal of making a game. Everything was fine when I ended up in a case that, so I researched, I did not find a solution in the ST. 1º the script, then the problem itself:

#include "stdafx.h" 
#include "finish.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <time.h>
#include <random>
#include "enemy.h"
#include "player.h"

using namespace std;

int main() {

finish d;

cout << "Welcome to the most epic game ever!" << "\n\n";

string action;

int rnd;
rnd = d.random_calc(1,2);

switch(rnd){

case 1:

    Monster *enm;
    enm->Encounter(enm->type);
    break;

case 2:

    Ninja *enm;
    enm->Encounter(enm->type);
    break;

}

cout << "Actual life:" /*<<*/   << endl;

Player p(10, 15, enm());
p.actionPrompt(&action, true);

cout << action; 

d.end();

}

To not take up too much space, follow the link to the github repository for this project(With all classes, recommend seeing them to make it easier to answer me)

The problem, after all. I have to choose, in the program, between creating one of two classes: "Monster" and "Ninja", both derived from the class "Enemy". Now, I get compilation errors for the created classes because they are created as locales (inside the switch) and cannot be accessed outside the switch.

Please, in case you know, Give me a solution!

  • Downvoter, could you please explain the reason to Pedro?

2 answers

2


You can set a "generic" pointer for the mother class Enemy just before the switch: Enemy *enm, and within the switch make the appropriate instantiations:

enm = new Monster();

...

enm = new Enemy();

Note that this was missing anyway in the original code; you cannot simply set a pointer and use it, you need to first pass a valid object address through the new.

  • 1

    Apparently it worked! Thank you :)

1

Simply declare a variable of type Enemy BEFORE THE switch and in the corresponding blocks you just initiating the variable, after all, it will already be declared.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.