尝试制作对象时出错

时间:2012-12-18 23:49:24

标签: c++ stl multimap

我正在尝试制作一个Question对象。 Question是班级,但我收到的错误是:

  

错误1错误C2440:'初始化':无法从Questions *转换为Questions

我正在尝试创建一个对象,因此我可以将其放入multimap类型的<int, Questions>

这是我的代码:

#include <iostream>
#include "Questions.h"
using namespace std;

Questions::Questions() {}
Questions::Questions(string question,string correctAnswer, string wrongAnswer1,string wrongAnswer2,string wrongAnswer3) {}

void Questions::questionStore() {
    Questions q1 = new Questions("Whats the oldest known city in the world?", "Sparta", "Tripoli", "Rome", "Demascus");
    string q2 = ("What sport in the olympics are beards dissallowed?", "Judo", "Table Tennis", "Volleyball", "Boxing");
    string q3 = ("What does an entomologist study?", "People", "Rocks", "Plants", "Insects");
    string q4 = ("Where would a cowboy wear his chaps?", "Hat", "Feet", "Arms", "Legs");
    string q5 = ("which of these zodiac signs is represented as an animal that does not grow horns?", "Aries", "Tauris", "Capricorn", "Aquarius");
    string q6 = ("Former Prime Minister Tony Blair was born in which country?", "Northern Ireland", "Wales", "England", "Scotland");
    string q7 = ("Duffle coats are named after a town in which country?", "Austria", "Holland", "Germany", "Belgium");
    string q8 = ("The young of which creature is known as a squab?", "Horse", "Squid", "Octopus", "Pigeon");
    string q9 = ("The main character in the 2000 movie ""Gladiator"" fights what animal in the arena?", "Panther", "Leopard", "Lion", "Tiger");

    map.insert(pair <int, Questions>(1, q1));
    map.insert(pair <int, string>(2, q2));
    // map.insert(pair<int,string>(3, q3));
    for (multimap <int, string, std::less <int> >::const_iterator iter = map.begin(); iter != map.end(); ++iter)
        cout << iter->first << '\t' << iter->second << '\n';
}

3 个答案:

答案 0 :(得分:1)

new表达式为您提供指向您动态分配的对象的指针。你需要做Questions* q1 = new Questions(...);。但是,如果您不需要动态分配(最终将对象复制到地图中),请不要打扰。只需Questions q1(...);

据推测,您将更改以下行(q2q3等)以匹配,但因为它们不符合您的预期。 (..., ..., ...)将评估为此逗号分隔列表中最右侧的项目。因此,您的q2行等同于string q2 = "Boxing";

答案 1 :(得分:1)

Questions q1 = new Questions语法不正确。

map.insert(pair <int, Questions>(1, q1));我可以看到你的map值类型是Questions对象而不是Questions指针,所以它应该是

Questions q1 = Questions ("Whats the oldest known city in the world?", "Sparta" , "Tripoli" , "Rome", "Demascus");

此外,您的变量映射与std :: map具有相同的名称,这是一个STL容器,建议您使用其他名称,例如:question_map;

修改

要允许<< iter->second,您需要为问题类型重载operator<<

std::ostream& operator<<(const std::ostream& out, const Questions& q)
{
    out << q.question;  // I made up this member as I can't see your Questions code
    return out;
}

答案 2 :(得分:0)

questionScore方法的第一行是问题:

Questions q1 = new Questions ...

new x返回指向x对象的指针,因此应将q1定义为指针。

Questions * q1 = new Questions ...