我在将对象添加到集合时遇到麻烦。
我在头文件中使用两个类,一个用于雇员,第二个用于经理。在经理类中,我想通过添加作为特定经理下属的员工来创建一组员工。首先,我创建一个空集,可以通过调用一个函数为其添加对象。
它看起来如下:
头文件
#ifndef EMPLOYEE_HH
#define EMPLOYEE_HH
#include <set>
#include <string>
#include <iostream>
using namespace std ;
class Employee {
public:
// Constructor
Employee(const char* name, double salary) :
_name(name),
_salary(salary) {
}
// Accessors
const char* name() const {
return _name.c_str() ;
}
double salary() const {
return _salary ;
}
private:
string _name ;
double _salary ;
} ;
class Manager : public Employee {
public:
//Constructor
Manager(const char* _name, double _salary):
Employee(_name, _salary),
_subordinates() {
}
// Accessors/Modifiers
void addSubordinate(Employee& empl) {
_subordinates.insert(empl) ; // Error: no macthing function call for .insert()
}
private:
set<Employee*> _subordinates ;
} ;
#endif
主脚本
#include <string>
#include <iostream>
#include "Employee.hh"
using namespace std ;
int main() {
Employee emp = ("David", 10000) ;
Manager mgr = ("Oscar", 20000) ;
mgr.addSubordinate(emp);
return 0;
}
编译时出现错误,提示无法调用任何匹配函数_subordinates.insert(empl)
。
元素的类型set
为Employee*
,但您要插入Employee
。
您可能会更改_subordinates.insert(empl);
为_subordinates.insert(&empl);
。
(更改的类型_subordinates
从set<Employee*>
到set<Employee>
可以修复编译器错误过,但似乎不符合要求。)
请注意,正如@KenmanTsang指出的那样,使用从堆栈变量获取的指针可能很危险。考虑有关使用智能指针用new
,如std::set<std::unique_ptr<Employee>> _subordinates;
。
顺便提一句:
Employee emp = ("David", 10000) ;
Manager mgr = ("Oscar", 20000) ;
应该
Employee emp ("David", 10000) ;
Manager mgr ("Oscar", 20000) ;
或(自c ++ 11起)
Employee emp = {"David", 10000} ;
Manager mgr = {"Oscar", 20000} ;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句