C ++:将对象添加到集合中 [英] C++ : adding an object to a set
问题描述
我在将对象添加到集合时遇到麻烦.
I am having trouble with adding an object to a set.
我在头文件中使用两个类,一个用于雇员,第二个用于经理.在经理类中,我想通过添加作为特定经理下属的员工来创建一组员工.首先,我创建一个空集,可以通过调用一个函数为其添加对象.
I use two classes in a header file, one for employees and a second one for managers. In the manager class I want to create a set of employees by adding employees who are subordinates for a particular manager. First I create a empty set for which I can add objects by calling a function.
它看起来如下:
头文件
#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)
无法调用任何匹配函数.
When compiling I get the error that no matching function can be called for _subordinates.insert(empl)
.
推荐答案
元素set
的类型为Employee*
,但是您要插入Employee
.
The element's type of set
is Employee*
, but you're inserting Employee
.
您可以将_subordinates.insert(empl);
更改为_subordinates.insert(&empl);
.
(将_subordinates
的类型从set<Employee*>
更改为set<Employee>
也可以修复编译器错误,但似乎与请求不匹配.)
(Changing the type of _subordinates
from set<Employee*>
to set<Employee>
could fix the compiler error too, but it seems doesn't match the request.)
请注意,如@KenmanTsang所指出的那样,使用从堆栈变量获取的指针可能很危险.考虑将智能指针与new
一起使用,例如std::set<std::unique_ptr<Employee>> _subordinates;
.
Note as @KenmanTsang pointed, using pointer got from stack variable might be dangerous. Consider about using smart pointer with new
, such as 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起)
or (since c++11)
Employee emp = {"David", 10000} ;
Manager mgr = {"Oscar", 20000} ;
这篇关于C ++:将对象添加到集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!