构造函数被忽略 [英] Constructor gets ignored
问题描述
我的构造函数被忽略了。这是我的代码:
my constructor gets ignored somehow. Here is my code:
我的类:
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();*/
};
构造函数字段()应该用'o'初始化我的4 wins字段,如果我想添加平铺它将x标记瓷砖的位置。
但如果我这样做
The constructor field() should initalize my 4 wins field with 'o's and if I want to add a Tile it will x mark where the tile is. But if I do
int main()
{
char x;
field FourWins;
//FourWins.setTile(3, 2);
x = FourWins.getTile(3, 2);
std::cout << x << std::endl;
return 0;
}
构造函数将被忽略,我得到一个weired符号,目前在我在看。
位置查找工作,因为如果我第一次设置和x到(3,2)它将打印我的x。
The constructor will get ignored and I get a weired sign which is most likely just currently at where I'm looking. The position finding works, becouse if I first set and x to (3,2) it will print me the x.
任何想法?
推荐答案
char [] [ ]
允许,但只有在构造 - 而不是赋值(和你的例子构造一个新的变量,而不是分配给成员变量) 。至少用C ++ 14你可以这样做:
The initialization syntax for char[][]
you used is allowed, but only at construction - not assignment (and your example constructed a new variable rather that assigned to the member variable). At least with C++14 you can do it like 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 }}
{}
};
考虑使用 std :: vector
code> std :: vector 或 std :: array
of std :: array
。与 char [5] [5]
相比,使用 std :: array
的唯一缺点是尺寸
Consider using std::vector
of std::vector
, or std::array
of std::array
instead. The only down side of using std::array
compared to char[5][5]
is that the sizes (5x5 in your case) must be known at compile time (just as in your 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;
}
用于数组初始化的语法很好,只是make如果您要启动现有的变数,请务必不要指派给新的变数。
The syntax you used for array initialization is fine, just make sure you don't assign to a new variable if you mean to initiate an existing one.
这篇关于构造函数被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!