2

I've this error when I try to save a number into my vector...

Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript

The code is:

class Elemento{
private:
    int Nodo;

public:
         Elemento(){};
         ~Elemento(){};
    void SetNumero(int x)    {  Nodo = x;  };
    int  GetNumero()         {  return Nodo; };
};    


class MagicSquare{
private:
    int    N;                             
    int    Possibili_N;                  
    int    Magic_Constant;                

    vector<Elemento> Square(int Possibili_N);    

public:
    MagicSquare()                   {    };
    ~MagicSquare()                  {    };

    void  Set_N(int x)              { N = x; };
    void  Set_PossibiliN(int x)     { Possibili_N = x; };
    void  Set_MagicConstant(int x)  { Magic_Constant = x; };

    . . .

    void SetSquare(int i, int x)    { Square[i].SetNumero(x); }; // got error here
    int  GetSquare(int i)           { return Square[i].GetNumero(); }; // got error here
};

I've got error whenever I use Square[i].method()...

I call a method that pass the index in the Square and the value to put in Elemento->Nodo, but I've to use a public method to access to private Nodo. The same with the GET. I want to get the value for displaying it.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Federico Cuozzo
  • 363
  • 1
  • 7
  • 20

3 Answers3

2

You seem to have declared Square as a function, not a variable.

Instead, declare vector<Elemento> Square; and initialize it in the constructor.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
tux3
  • 7,171
  • 6
  • 39
  • 51
  • So, How can I initialize it in the constructor? I have to calculate before N, Possible_N and MagicCostant and then I can dimension the vector... – Federico Cuozzo Apr 16 '15 at 15:49
  • @FedericoCuozzo you can use [`vector::resize`](http://www.cplusplus.com/reference/vector/vector/resize/) if you have to compute something first. – tux3 Apr 16 '15 at 15:50
1

You declared Square as a function, not a variable. So Square[i] is not valid.
Change

vector<Elemento> Square(int Possibili_N); 

to

vector<Elemento> Square;

or call it using

Square(i)

if it is actually a function.

If you change it to a variable, you need to be sure to initialize it properly, preferably in the constructor.

dwcanillas
  • 3,562
  • 2
  • 24
  • 33
1

Your line vector<Elemento> Square(int Possibili_N); is know as C++ most vexing parse.

Instead of declaring a member variable, as intended, you are declaring a function taking an int and returning a vector.

Instead, setup the member vector (and all other member variables) in the constructor initialization list:

class MagicSquare{
private:
    int N;
    int Possibili_N;
    int Magic_Constant;
    vector<Elemento> Square;

public:
    MagicSquare( int n, int p, int m ) :
        N( n ),
        Possibili_N( p ),
        Magic_Constant( m ),
        Square( p ) {
    }
...
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171