Undeclared Identifier

I get the following error: Use of undeclared identifier 'i'
In the class PlayerClass. How would I go about fixing this?

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
62
63
64
65
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <tuple>
#include <vector>
#include <array>
#include <valarray>
#include <fstream>
#include <iomanip>
#include <cassert>
using namespace std;


struct Ability {
    string name;
    int level_adder;
    
    int cost(int level, int intelligence) {
        return (level + level_adder) * intelligence;
    }
    
    bool can_afford(int level, int intelligence, int manna) {
        return cost(level, intelligence) <= manna;
    }
    
    void show(int level, int intelligence) {
        std::cout << name << "[" << cost(level, intelligence) << " manna]\n";
    }
};

class PlayerClass {
    string name;
    vector<Ability> abilities;
    size_t ability_count() { return abilities.size(); }
    
    void show(int level, int intelligence) {
        for (int i=0; i<abilities.size(); i++)
            std::cout << "[" << i << "] ";
            abilities[i].show(level, intelligence);
    }
    
    Ability const &operator[](size_t index) const {
        return abilities.at(index);
    }
};

class Player {
    string name; // player name
    int health = 100; // player health
    int mana = 20; // player mana
    int strength = 5; // strength [what it does]
    int intelligence = 5; // intelligence [what it does]
    int agility = 5; // agility [what it does]
    int level = 0; // player level
    int xp = 0; // experence
    int xprequired = 50; // amount of xp is required to level up
    int xpincrease = 25; // increases each level, adds to 'xprequired'
};

int main() {
    return 0;
}
Last edited on
If you don't have brackets in your for loop only the next statement becomes apart of its scope.

1
2
3
4
 
 for (int i=0; i<abilities.size(); i++) //variable i declared in for loop
 std::cout << "[" << i << "] ";//still part of for loop
 abilities[i].show(level, intelligence);//not part of for loop, out of scope, compiler does not know what "i" is. 
Last edited on
Line 40: This is the only line that is within scope of the for loop and therefore the only line where i is in scope. If you want lines 40 and 41 to both be in scope of the for loop, use {} to bracket both lines.

Topic archived. No new replies allowed.