[英]How to create a constructor which takes in a char array?
我有一個類,它接受一個由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;
}
我想創建一個帶有數組的構造函數作為其參數,其中數組已經具有設置大小,然后從中創建一個對象。 要傳遞給對象的數組將始終具有相同的大小,這是構造函數設置為要接受的數組的大小。
您正在使用Message ms1(input[], 6);
在主函數中,嘗試將其更改為Message ms1(input, 6);
。 原因是你已經聲明了數組char input[]
並且在聲明它不是input[]
之后你必須將它作為input
引用。
Message(char input[], int size);
在參數聲明中使用[]
只是語法糖,編譯器會將char input[]
解釋為char* input
。
this->input[InputBufferSize] = 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);
另外,在復制input
數組之前,應確保size
不超過InputBufferSize
:
size = std::min(size, InputBufferSize);
Message ms1(input[], 6);
這也不是合法代碼。 在將數組傳遞給參數時,您需要刪除[]
:
Message ms1(input, 6);
std::cin >> charinp;
另外,您可以使用std::cin.get()
代替,並從代碼中刪除charinp
(因為您無論如何都不使用它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.