c++ - Constructor gets ignored -


my constructor gets ignored somehow. here code:

my class:

class field { private:     char playfield[5][5];  public:     char o = 'o';     field()     {         char playfield[5][5] = { { o, o, o, o, o }, { o, o, o, o, o }, { o, o, o, o, o }, { o, o, o, o, o }, { o, o, o, o, o } };     }       void settile(int x_val, int y_val)     {         playfield[x_val][y_val] = 'x';     }     char gettile(int x_val, int y_val)     {         return playfield[x_val][y_val];      }        /*field::~field();*/ }; 

the constructor field() should initalize 4 wins field 'o's , if want add tile x mark tile is. if do

int main() {     char x;      field fourwins;     //fourwins.settile(3, 2);     x = fourwins.gettile(3, 2);     std::cout <<  x << std::endl;      return 0; } 

the constructor ignored , weired sign @ i'm looking. position finding works, becouse if first set , x (3,2) print me x.

any ideas?

ideone example here

the initialization syntax char[][] used allowed, @ construction - not assignment (and example constructed new variable rather assigned member variable). @ least c++14 can this:

class field { private:     char o = 'o';     char playfield[5][5]; public:     field() : playfield{{ o, o, o, o, o }, { o, o, o, o, o },                          { o, o, o, o, o }, { o, o, o, o, o },                          { o, o, o, o, o }}     {} }; 

consider using std::vector of std::vector, or std::array of std::array instead. down side of using std::array compared char[5][5] sizes (5x5 in case) must known @ compile time (just in example)

#include <iostream> #include <array> #include <vector>  using namespace std;  int main() {     char o='a';      // c++11 or later:     std::array<std::array<char,5>, 5> playfield2{{{o,o,o,o,o},{o,o,o,o,o},                                   {o,o,o,o,o},{o,o,o,o,o},{o,o,o,o,o}}};      // or: (c++11 or later)     std::array<std::array<char,5>, 5> playfield;     for(auto& row : playfield){         for(auto& place : row){             place=o;         }     }     cout << playfield[2][3] << std::endl;      // or: (c++98 or later)      std::vector<std::vector<char>> playfieldvec(5,std::vector<char>(5,o));     cout << playfieldvec[2][3] << std::endl;  } 

the syntax used array initialization fine, make sure don't assign new variable if mean initiate existing one.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -