【发布时间】:2020-12-03 13:07:28
【问题描述】:
我创建了一个名为“信”的类:
class Letter
{
char letter{};
bool guessed{ false };
public:
void setLetter(std::string);
};
我想创建一个“字母”类的数组。数组的大小应该是用户输入字符串的大小,如果可能,字符串的每个字母都应该存储在字母对象的 1 个元素中。 我尝试了以下方法:
std::string word;
Letter test[] = word;
"initialization with {...} expected for aggregate object"
std::string word;
Letter test[word.length()]; // and then iterate through each element of the string
"expression must have a constant value"
编辑: 解决了
std::string word;
std::vector<Letter> test;
for (int i = 0; i < word.length(); i++)
{
test[i].setLetter(word[i]);
}
【问题讨论】:
-
当您需要动态大小的数组时首选
std::vector。 -
你能用
vector吗? -
@GenoC 当然,我只是更习惯于数组
-
setLetter(std::string)应该是setLetter(char); -
letter成员是private。大概是setLetter负责设置吧。但它需要一个完整的std::string而不仅仅是一个字母。目前尚不清楚它是如何工作的,如果输入不完全是 1 个字母,我无法想象它应该做什么。您的意思是改用void setLetter(char)吗?