简体   繁体   English

C ++初始化类的char数组成员

[英]c++ initializing char array member of class

in my c++ project I have class with two members. 在我的C ++项目中,我有两个成员的课程。 the char array member I have problems with. 我遇到问题的char数组成员。

class frame_message
{
public:
    explicit frame_message(const unsigned int id, const char data[]) :id_(id), data_{ *data }{};
    // only the first char 'a' is copied to `data_`
    char* get_data() { return data_; };
    void get_data(char** data) { *data = data_; };
private:
    unsigned int id_; char data_[8];
};

now from main method I want to send another char array used to initialize the class array. 现在从main方法中,我想发送另一个用于初始化类数组的char数组。

main
{
char data[8]={'a','b','c'} // indexs 3 to 7 are '\0'
char data2[8];
char data3[8];
frame_message myMessage(0xF004,data); // the data is passed as "abc"
data2 = myMessage.get_data(); // analysis error
myMessage.get_data(&data3); // runtime exception
}

How should I initialize the private member of class with exactly the data array send to constructor? 我应该如何使用将数据数组发送给构造函数的形式来初始化类的私有成员?

also for for get_data functions what data type should be passed? 同样对于get_data函数,应该传递什么数据类型?

ps I am new in c/c++ and yet get confused in pointers, references and specially char and char* ps我是c / c ++的新手,但对指针,引用和特别是charchar*感到困惑

For the constructor, it would be a good idea to pass a length parameter as well because you can accept only up to 8 bytes. 对于构造函数,最好也传递一个length参数,因为您最多只能接受8个字节。 Then, if your length is <= 8 : 然后,如果您的长度是<= 8:

memcpy(data_, data, length)

Same thing in your parameterized get_data, so it would be: 您的参数化get_data中的内容相同,因此可能是:

memcpy(*data, data_, 8) /* Assuming that they provide long enough array. */

It is good practice when dealing with arrays to always include length, and when dealing with pointers to check if they are NULL - I'll leave this to you. 在处理数组时总是包含长度,在处理指针以检查它们是否为NULL时,这是一个好习惯-我将留给您。 The reason you were getting errors is because you cannot assign a pointer to a statically declared array - it has a fixed address, you can only change the content. 出现错误的原因是因为无法将指针分配给静态声明的数组-它具有固定的地址,因此只能更改内容。

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

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