我有一个类,它接受由constexpr指定的大小的char数组。

Message.h:

constexpr size_t InputBufferSize = 32;

class Message
{
private:
    char input[InputBufferSize];
    int size;
public:
    //constructor
    Message(char input[], int size);
    //deconstructor
    ~Message();

    int getSize();
};

我对如何定义构造函数感到困惑,然后由于char数组而使用构造函数创建该类的新实例。这是我的尝试(我尝试过的一些方法):

Message.cpp:
#include "Message.h"

Message::Message(char input[], int size) {
    this->input[InputBufferSize] = input[];
    this->size = size;
}

Message::~Message() { }


int Message::getSize() {
    return size;
}

main.cpp:
#include <iostream>
#include "Message.h"

int main()
{
    char charinp;
    char input[InputBufferSize] = { 'a','b','c','d','e','f' };

    Message ms1(input[], 1);

    std::cout << ms1.getSize() << std::endl;

    std::cin >> charinp;

    return 0;
}

我想创建一个带有数组作为其参数的构造函数,该数组已经具有设置的大小,然后从中创建一个对象。传递给对象的数组将始终具有相同的大小,这是构造函数设置为要接收的数组的大小。

最佳答案



在参数声明中使用[]只是语法糖,编译器会将char input[]解释为char* input



这不是法律法规。您需要使用(std::)memcpy()std::copy() / std::copy_n()将一个数组复制到另一个数组:

memcpy(this->input, input, size);
std::copy(input, input + size, this->input);
std::copy_n(input, size, this->input);

附带说明,在复制size数组之前,应确保InputBufferSize不超过input:
size = std::min(size, InputBufferSize);



这也不是法律法规。将数组传递给参数时,需要删除[]:
Message ms1(input, 6);



附带一提,您可以改用std::cin.get(),并从代码中删除charinp(因为无论如何您都不会使用它)。

关于c++ - 如何创建一个接受char数组的构造函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54890801/

10-11 19:35
查看更多