初始化二维数组在类的构造函数在C ++中 [英] Initializing 2D Array In Class Constructor in C++

查看:436
本文介绍了初始化二维数组在类的构造函数在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在头文件中定义一个二维数组

I define a 2D array in my header file

char map[3][3];

我怎样才能在类的构造像这样初始化值

How can I initialize the values in the class constructor like this

 map = {{'x', 'x', 'o'},
       {'o', 'o', 'x'},
       {'x', 'o', 'x'}};


推荐答案

首先,有分配和初始化之间的差。该OP标题大约是初始化。

Firstly, there is a difference between assignment and initialization. The OP title is about initialization.

其次,你还没有告诉我们,如果你的二维数组是类成员(静态/非静态)或命名空间的变量。

Secondly, you have not told us if your 2D array is a class member(static/non static) or a namespace variable.

- 由于你提到在类的构造函数初始化它,我假设它是一类非静态成员,这是因为:

-Since you mentioned about initializing it in the class constructor, I am assuming that it is a class non static member, because:

$ 12.6.2 / 2 - 除非
  MEM-初始化-ID名称
  构造函数的类,非静态数据
  构造函数的类的成员,或
  那直接或虚拟的基础
  课堂上,MEM-初始化为
  病态的。

$12.6.2/2 - "Unless the mem-initializer-id names the constructor’s class, a non-static data member of the constructor’s class, or a direct or virtual base of that class, the mem-initializer is ill-formed."

此外,由于C ++ 03的成员数组不能在构造函数初始化列表中的OP(不知道的C ++ 0x)的情况下,虽然初始化

Further, as of C++03 the member array cannot be initialized in the constructor initializer list for the case in OP(not sure about C++0x) though.

- 如果您的二维数组是类的静态成员,你应该为你做(有轻微的变化)进行初始化,而不是在构造函数中。这应该在封闭的空间范围,任何翻译单位进行一次且仅一次。

-If your 2D array is a static member of your class, you should initialize it as you did (with a slight change), but not in the constructor. This should be done in the enclosing namespace scope once and only once in any of the translation units.

char (A::map)[3][3] = {{'x', 'x', 'o'}, 
       {'o', 'o', 'x'}, 
       {'x', 'o', 'x'}};

-Alternatively,如果您的二维阵列是命名空间范围变量,阵列的定义应取出的头文件(除非它也是静态的),因为它会导致重新定义误差并进行定义并初始化一次和只有在任何翻译单元,因为一旦

-Alternatively, if your 2D array is a namespace scope variable, the definition of the array should be taken out of the header file (unless it is also static) as it will cause a redefinition error and be defined and initialized once and only once in any translation unit as

char map[3][3] = {{'x', 'x', 'o'}, 
       {'o', 'o', 'x'}, 
       {'x', 'o', 'x'}}; 

这篇关于初始化二维数组在类的构造函数在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆