C++ 在类中使用向量创建类

C++ 在类中使用向量创建类,c++,class,vector,C++,Class,Vector,我有一个类,它包含一个向量if字符串,所以我可以得到无限的答案(我用它来学习,基本上是通过模拟测试)。然而,当我创建thingy时,它会在试图在向量中包含值时对我发火。我试过很多方法让它工作,但是不行 #include <iostream> #include <vector> using namespace std; string input; class answer { public: vector<string> answers; };

我有一个类,它包含一个向量if字符串,所以我可以得到无限的答案(我用它来学习,基本上是通过模拟测试)。然而,当我创建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));
}
#包括
#包括
使用名称空间std;
字符串输入;
课堂答案{
公众:
矢量答案;
};
班达{
公众:
字符串问题;
回答问题;
字符串正确;
};
无效提问(qANDa bob){
cout
qANDa
有三个字符串,因此初始值设定项可以看起来像
{“一”、“二”、“三”}

哦,对不起,我没有看到中间的是
答案
,这是一个
向量
,而不仅仅是一个
字符串
。如果它是一个字符串,上面的方法就行了

qANDa thingy = {"The correct answer is \"A\". What's the correct answer.", answer(), "A"};
还请注意末尾添加的分号


当无法保证全局字符串变量
input
的长度>=1时,
askQuestion
input[0]
中存储字符的代码出现问题

为了解决这个问题,我建议将
input
的类型从
std::string
更改为
char



使用全局变量来传递函数结果充满危险,而应考虑使用函数结果。您会发现它们在C++教科书中讨论过。

< P> >您的类<代码>回答< /代码>不能仅从空括号<代码> {} /COD> >初始化,您可以给出默认构造的RValk引用:
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));

您是否尝试将
answer()
替换为
{}空括号?我没用,谢谢。这个建议。如果你把它加上答案,我可以把它标记为正确的。还有,在定义它的时候有没有办法回答?我不是在学习C++,但是答案需要比一个字符大。虽然谢谢你告诉我,我还是会确定的。要么添加至少一个字符,要么强制用户添加。谢谢,但我现在遇到了更多问题。我添加了thingy.answers.a.push_back(“a”);为了添加一个值,我会在中途显示以下代码:if(u n>=size())this->u throw_out_of_range();return this->u begin_u[u n]}你知道怎么了吗?我猜某个东西的大小是0(我很确定它的值是0)。谢谢,当我看到我把事情搞砸的时候,我真的意识到我有多愚蠢。那些敢于提问的人永远不会是愚蠢的人。那些不问的人是被抛在后面的哑巴。