2013-12-12 30 views
0

我有一个类,其中包括一个向量如果字符串,所以我可以有无限的答案(我用这个来研究本质上做模拟测试)。然而,当我创造东西的时候,它试图在矢量中创造价值时会生我的气。我已经尝试了很多方法来使它起作用,但它不能。在类中创建类与矢量

#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)); 
} 

我试图把字符串的括号内,我已经使用了括号内括号试过了,我已经把括号内的括号内的字符串,但没有它的工作原理。

+0

您是否尝试将'answer()'而不是{{}'空括号? –

+0

我没有,那工作。感谢您的建议。如果您将其添加为答案,我可以将其标记为正确。 – dunnmifflsys

+0

另外,有没有一种方法可以在定义答案时加入? – dunnmifflsys

回答

1

你的类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)); 
+0

谢谢,但我现在有更多的问题。我已经添加了行thingy.answers.a.push_back(“A”);为了增加一个值,我得到这个代码在中途显示:if(__n> = size())this - > __ throw_out_of_range(); return this - > __ begin _ [__ n]; }你知道什么是错的吗?我猜有些东西的大小为0(_n的值为0,我很确定)。 – dunnmifflsys

+0

@newbie查看我的更新... –

+0

谢谢,当我看到我弄糟的地方时,我真的意识到自己有多愚蠢。 – dunnmifflsys

0

qANDa有三个字符串,所以初始化程序可以看起来像{"one", "two", "three"}

对不起,我没有看到中间是answer,这是一个vector<string>,而不是一个单一的string。如果它是一个单一的字符串,上述将工作。只要做

qANDa thingy = {"The correct answer is \"A\". What's the correct answer.", answer(), "A"}; 

还要注意在最后加上分号。


有一个与askQuestion代码存储字符input[0],当有不保证全局字符串变量input具有长度> = 1

为了解决这个问题,我建议改变的问题inputstd::stringchar


使用全局变量传递函数结果充满了危险。相反,请考虑使用函数结果。你会发现他们在你的C++教科书中讨论过。

+0

实际上,我并没有为C++学习,但答案需要能够比一个字符更大。虽然感谢告诉我,但我会确保要么添加至少一个字符,要么强制用户访问。 – dunnmifflsys