Undeclared variable

Hello everybody,

I'm currently working on a simple ASCII-game in the console, and I've stumbled upon a problem while making a class for a "monster".

To explain my problem, let me first explain my projection on the game.

I'm using for the view 4 variables, the x and y of the view, and the width and height (called xView, yView, wView and hView). Each variable is declared at the beginning of the code, which looks like this:

MAIN.CPP
1
2
3
4
5
6
7
8
9
#include<iostream>
#include<string>
#include<windows.h>
#include<stdlib.h>
#include<math.h>
#include "monsterclasses.cpp"
using namespace std;

int xView=0, wView=40, yView=0, hView=20, xPlayer=16, yPlayer=12, wRoom=64, hRoom=48;


The code for in the file "monsterclasses.cpp" is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include<iostream>
#include<math.h>
#include<string>
#include<stdlib.h>
#include<windows.h>
using namespace std;

class CMonster{
    int x,y, hp, hpmax, level;
    char symbol;
    bool attacked, dead;
    string name;
  public:
    CMonster ();
    CMonster (int,int,char,int);
    void dObject();
    void aMove();
};

CMonster::CMonster (){
    x = 20;
    y = 10;
    dead = false;
    attacked = false;
    symbol = 'a';
    level = 1;
    hp = 7;
    hpmax = 7;
    attacked = false;
}

CMonster::CMonster (int a, int b, char c, int d){
    x = a;
    y = b;
    symbol = c;
    dead = false;
    attacked = false;
    level = d;
    hp = floor(sqrt(level)*2)+5;
    hpmax = hp;
}

void CMonster::dObject(){
    if (dead == false && x >= xView && x < xView+wView && y >= yView && y < yView+hView){
        curPos(20-xView+x,1-yView+y);
        cout << symbol;
    }
}

void CMonster::aMove(){
    int a;
    a = rand() %5;
    switch (a)
    {
        case 0: {x = max(0,x-1);}; break;
        case 1: {y = max(0,y-1);}; break;
        case 2: {x = min(wRoom,x+1);}; break;
        case 3: {y = min(hRoom,y+1);}; break;
        case 4: {}; break;
    }
}


But when I try to compile the code, the compiler (Code::Blocks) gives me the following error:
error: 'xView' undeclare (first to use in this function)

and for all the 5 other variables (yView, wView, hView, wRoom, hRoom) as well...

Now I wonder, is this an errorr in the main code, or should I just place the code from "monsterclasses.cpp" in the main code?

- Ojima
Last edited on
you give this error because you declare the 'cView' and the others variable 'after' the #include monsterclasses.cpp , those variables not exist for CMonster. However, i just suggest you to split the 'definition' and the 'implementation' of the class 'CMonster' into to file '.h' for definition and '.cpp' for implementation. Then you include in the main.cpp only the .h file of CMonster.
Topic archived. No new replies allowed.