首页 > 解决方案 > 使用映射参数的转换构造函数给出错误

问题描述

我制作了一个小型控制台程序,其中有一个名为 Class_Room 的类。我可以用它制作学校教室的对象,并在其中存储学生姓名、卷号和年龄。学生数据存储在地图中。我想像这样制作教室对象:

Class_Room class8C = {
       {"student x", 2},  //2 for rollnumber
       {"student y", 3}
};

所以我做了一个转换构造函数:

Class_Room(std::map<int, std::string> map) {
        for (std::pair<int, std::string> value : map) {
            student_data[value.first] = { value.second, "NIL" };
        }
    }

但我得到错误:没有构造函数 Class_Room::Class_Room 的实例匹配参数列表

“初始化”:无法将“初始化列表”转换为 Class_Room

这是我的整个代码:

#include <iostream>
#include <vector>
#include <string>
#include <map>

class Class_Room {
public:

    Class_Room(std::map<int, std::string> map) {
        for (std::pair<int, std::string> value : map) {
            student_data[value.first] = { value.second, "NIL" };
        }
    }

    void new_student(int roll, std::string name, int age = 0)
    {
        data.clear();
        data.push_back(name);
        if (age != 0) {
            data.push_back(std::to_string(age));
        }
        else {
            data.push_back("NIL");
        }
        student_data[roll] = data;
    }

    std::map<int, std::vector<std::string>> get_student_data_map()
    {
        return student_data;
    }


private:
    std::map<int, std::vector<std::string>> student_data;
    std::vector<std::string> data;
};

std::ostream& operator<< (std::ostream& output, Class_Room classroom)
{
    std::map<int, std::vector<std::string>> student_data = classroom.get_student_data_map();

    for (std::pair<int, std::vector<std::string>> value : student_data) {
        output << value.first << " => " << value.second[0] << ", " << value.second[1] << "\n";
        
    }
    return output;
}


int main() {
    Class_Room class8C = {{"Ihsan", 2}};
    std::cout << class8C;
}

我是 C++ 的初学者,不知道出了什么问题,任何帮助将不胜感激。

标签: c++

解决方案


这个答案还有更多内容,但我会选择能解决你问题的东西,然后会尝试解释一些更有趣的部分,以便你从中学到一些东西。

GIST:你的地图正好相反

// your map has keys of type int, values of type string
Class_Room(std::map<int, std::string> map) { // pairs of <int, string>
        for (std::pair<int, std::string> value : map) {
            student_data[value.first] = { value.second, "NIL" };
        }
}

// and then you want to insert pairs of <string, int>
// keys of type string, values of type int
// like: {"Ihsan", 2}

颠倒这些应该让你走上正确的轨道。

// Class_Room class8C = {{2, "Ihsan"}}; // but this is not enough!
// you actually need something along these lines:
    Class_Room class8C{
        std::map<int, std::string>{{2, "Ihsan"}}};

// or

    Class_Room class8C{ 
        { // creates the map
            { // creates the pair to insert
                2, std::string("Ihsan") 
            }
        }
    };

你得到的错误是因为编译器试图找到正确的构造函数并且它失败了。

首先,您需要一个映射来传递给您的构造函数。在调用您的 ctor 之前,编译器必须想办法创建该映射(如果该映射尚不存在)。

如果您查看构造函数std::map,您会注意到第 5 个采用初始化列表:https ://en.cppreference.com/w/cpp/container/map/map

该初始值设定项列表的 value_type 模板也是:<int, string>,与映射本身相同。所以顺序很重要。

您也可以事先创建地图,但我想您需要简洁的代码。


推荐阅读