4

我有一个与 C++ 类成员初始化有关的问题。以下代码说明了我的问题:

class ABCD
{
public:
    ABCD():ObjNum(3){};
    ~ABCD() {};
     static const  unsigned char getByte[8];
     const int ObjNum;


};

const unsigned char ABCD::getByte[8] = {
    'a','b','c','d','e','f','g','h'
};

int main() 
{
     ABCD test;
     cout<<test.getByte[3]<<endl;


     return 0;
}

上面的代码工作得很好,但是现在如果我不将 getByte[8] 设置为静态,我怎么能初始化这个类呢?我尝试过这种方式,但失败了:

class ABCD
{
public:
    ABCD():ObjNum(3),getByte('a','b','c','d','e','f','g','h')
    {

    };
    ~ABCD() {};
    const  unsigned char getByte[8];
     const int ObjNum;


};



int main() 
{
     ABCD test;
     cout<<test.getByte[3]<<endl;


     return 0;
}

我得到的错误如下:

 error C2536: 'ABCD::ABCD::getByte' : cannot specify explicit initializer for arrays

我了解我收到错误的原因,但我不知道如何解决它。任何的想法?谢谢!

4

5 回答 5

4

在 C++11 中,您可以像这样初始化它:

ABCD() : ObjNum(3), getByte{'a','b','c','d','e','f','g','h'} {}

但是,如果您要使用 C++11,最好std::array按照其他人在评论中的建议使用。然后,您可以像这样定义数组:

const std::array<unsigned char, 8> getByte;

并以这种方式初始化它(注意双括号):

ABCD() : ObjNum(3), getByte{{'a','b','c','d','e','f','g','h'}} {}
于 2012-08-21T08:08:40.013 回答
3

在 C++11 中,您可以像这样初始化数组:

ABCD() : getByte { 'a','b','c','d','e','f','g','h' }
{ ... }
于 2012-08-21T08:08:42.713 回答
1

如果你有一个 C++11 兼容的编译器,你应该可以这样使用:

ABCD():ObjNum(3),getByte{'a','b','c','d','e','f','g','h'}

但是,如果您的编译器无法处理,您必须在构造函数中手动初始化数组,可以是逐个元​​素地初始化数组,也可以是拥有另一个数组,然后执行 eg memcpy

编辑:如果您的编译器无法处理 C++11 语法,那么您很不走运。但是,至少从 4.4 版开始,GCC 以及 VC++2010 都可以处理它。因此,除非您有强制要求使用“古老”编译器的要求,否则这应该不是问题。

于 2012-08-21T08:08:19.700 回答
1

最好放弃 C 数组。在 C++ 中,最好使用 std::string。在这种情况下:

class A
{
public:
   A() : s("abcdefgh") {}

private:
   std::string s;
}

在 C++11 中,您可以使用 std::array 并使用 std::initializer_list

class A
public:
   A() : s{'a','b','c','d','e','f','g','h'} {}

private:
   std::array<8> s;
}
于 2012-08-21T08:15:14.503 回答
1

在 C++03 中,您可以将成员更改为boost::array类型,并在构造函数中使用返回的函数对其进行初始化boost::array<char,8>

于 2012-08-21T08:16:06.003 回答