简体   繁体   English

如何在类内初始化char数组?

[英]How to Initialize a char array inside a class?

I was about to initialize a char array inside a class as 我正要初始化一个类内的char数组为

class a{
    char a[25];
};

a::a(){
    a[] = {'a','b','c'};
}

but gives compile time error. 但是会给出编译时错误。

If your compiler supports the C++11 feature, you can do it like this: 如果您的编译器支持C ++ 11功能,则可以这样进行:

a::a() :arr({'a','b','c'})
{}

Otherwise, you'll have to do it manually, or you can use a function like memcpy : 否则,您将必须手动执行此操作,或者可以使用类似memcpy的函数:

a::a() {
    memcpy(arr,"abc",3);
    // The other initialization method will fill the rest in with 0,
    // I don't know if that's important, but:
    std::fill(arr + 3, arr + 25, '\0');
}

Or, as suggested by ephemient: 或者,根据短暂的建议:

a::a() {
    strncpy(arr, "abc", 25);
}
class LexerP
{   
public:
    char header[5];
    void h();
    void echo(){printf(" salut les gars ...\n \n");};   
};


void LexerP::h()
{
    int i=0;
    int j=0;

    char headM[5] ={0x07,0x0A,0x05,0x00,0x05};
    /*  for (i=0;i<strlen(this->header);i++)
    header[i]=headM[i];*/
    strcpy(this->header,headM)
};



main()
{
    LexerP *M=new (LexerP);
    M->echo();
    M->h();
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM