【问题标题】:Adding a class to a map将类添加到地图
【发布时间】:2014-07-26 15:44:48
【问题描述】:

我正在尝试将类对象添加到地图中,这就是我所拥有的:

#include<vector>
#include<map>
#include<stdio.h>
#include<string>
#include<iostream>

using namespace std;

class Student{
    int PID;
    string name;
    int academicYear;
public:
    Student(int, string, int);
};

Student::Student (int P, string n, int a) {
    PID = P;
    name = n;
    academicYear = a;
}

void createStudent(map<string, Student>);

int main(int argc, char** argv){

    map <string, Student> studentList;

    createStudent(studentList);
}


void createStudent(map<string, Student> studentList){

    int PID;
    string name;
    int academicYear;

    cout << "Add new student-\nName: ";
    getline(cin, name);
    cout << "PID: ";
    cin >> PID;
    cout << "Academic year: ";
    cin >> academicYear;

    Student newstud (PID, name, academicYear);

    studentList[name] = newstud;  //this line causes the error: 
                                  //no matching function for call to 
                                  //'Student::Student()'
}

我不明白为什么要在那里调用构造函数,我认为 newstud 应该已经从上一行构造了。当我尝试将newstud添加到地图时,谁能解释发生了什么?

【问题讨论】:

  • 阅读reference。另请注意,您对studentList 的更改不会产生任何影响。
  • 你是按值传递的。如果您尝试传递 int 参数并期望 int 在函数返回时神奇地改变,那么您的错误也没有什么不同。而是通过引用传递。

标签: c++ class map


【解决方案1】:
  • 第一个问题

std::map::operator[] 将使用默认构造函数将新元素插入到容器中(如果它不存在),在您的情况下它不存在并且即使您提供一个也可能没有意义。

所以在这种情况下使用std::map::insert

  • 第二个问题

即使您使用studentList.insert(std::make_pair(name, newstud)); 成功插入,它也不会反映main ( ) 中原始映射studentList 的更改,除非您在createStudent 的函数定义和声明中使用引用类型

所以用

void createStudent(map<string, Student>& );

【讨论】:

    【解决方案2】:

    为了使用函数添加条目,你应该让你的参数studentList通过引用传递。

    而不是

    studentList[name] = newstud; 
    

    使用:

    studentList.insert(std::make_pair(name, newstud));
    

    不过,只是一个建议。

    【讨论】:

    • 这不仅仅是一个建议
    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2012-02-21
    • 2014-08-13
    • 2011-04-29
    • 2015-12-23
    相关资源
    最近更新 更多