[英]Creating class with vector in class
我有一個包含向量(如果有字符串)的類,因此我可以有無限的答案(我正在通過本質上進行模擬測試來研究它)。 但是,當我創建thingy時,它在嘗試在向量中包含值時會生氣。 我已經嘗試了很多方法來使其正常工作,但是不能。
#include <iostream>
#include <vector>
using namespace std;
string input;
class answer {
public:
vector<string> answers;
};
class qANDa {
public:
string question;
answer answers;
string correct;
};
void askQuestion (qANDa bob) {
cout << bob.question;
getline(cin, input);
input[0] = tolower(input[0]);
if (input == bob.correct) {
cout << "Correct!\n";
} else {
cout <<"Incorrect. Study more. Loser.\n";
};
}
vector<qANDa> thingys;
int main(int argc, const char * argv[]) {
qANDa thingy = {"The correct answer is \"A\". What's the correct answer.", {} "A"}
askQuestion(thingys.at(0));
}
我試過將字符串放在括號內,試過在括號內使用括號,在字符串內將括號內的字符串放在括號內,但都無效。
您不能僅從方括號{}
初始化類answer
,但是您可以提供默認的構造右值引用:
qANDa thingy =
{ "The correct answer is \"A\". What's the correct answer."
, answer()
, "A" }
另請注意 ,此時您正在打電話
askQuestion(thingys.at(0));
thingys
包含任何元素。 更改為
qANDa thingy =
{ "The correct answer is \"A\". What's the correct answer."
, answer()
, "A"};
thingys.push_back(thingy);
askQuestion(thingys.at(0));
qANDa
有三個字符串,因此初始化程序看起來像{"one", "two", "three"}
。
哦,對不起,我沒有看到中間類型是answer
,它是vector<string>
,而不僅僅是單個string
。 如果它是單個字符串,則上面的命令會起作用。 只是做例如
qANDa thingy = {"The correct answer is \"A\". What's the correct answer.", answer(), "A"};
還要注意最后添加的分號。
當不能保證全局字符串變量input
長度> = 1時, askQuestion
代碼在input[0]
存儲字符時存在問題。
為了解決這個問題,我建議將input
類型從std::string
更改為just char
。
使用全局變量來傳遞函數結果充滿了危險。 而是考慮使用函數結果。 您會在C ++教科書中找到討論的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.