c++ - 尝试制作对象时出错

标签 c++ stl multimap

我正在尝试制作 Question目的。 Question作为类(class),但我收到一个错误:

Error 1 error C2440: 'initializing' : cannot convert from Questions * to 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';
}

最佳答案

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

关于c++ - 尝试制作对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943402/

相关文章:

c++ - 关于内存的动态特性,C++ 示例

c++ - 如何为具有 std::stringstream 成员的类编写复制构造函数?

java - 使用Java Stream将List和String的列表转换为Map

c++ - Windows - 从消息队列中删除与键盘相关的消息

c++ - 在 C++ 的 SFML 中居中​​形状/对象

c++ - 如何从 Arduino 库中读取数组?

STL 算法的 C++ "smart"谓词

c++ - 迭代器和重载 << 运算符

java - 如何对 Guava 多图进行排序? (关键=日期)

C++:std::map 中的引用计数值; std::multimap 是更好的选择吗?