【发布时间】: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在函数返回时神奇地改变,那么您的错误也没有什么不同。而是通过引用传递。