成员函数C ++初学者

时间:2013-10-26 02:28:30

标签: c++ class member-functions

所以基本上我正在玩一个简单的员工类,假设将名称映射到唯一的ID号。现在就是这样的。我想创建一个不带参数的成员函数,但返回名称和员工ID的映射。我希望这个电话很直观,例如。 employee.map_this() // returns a map

class Employee
{
public:
    Employee() = default;
    Employee(const string& pname);  
    Employee& operator=(const Employee&) = delete; 
    Employee(const Employee&) = delete;

private:
    const string name;
    static int ID_no;
    const string employee_ID;
    map<const string, const string> map_this();
};

int Employee::ID_no = 0001;

Employee::Employee(const string& pname) : name(pname), employee_ID(to_string(ID_no))
{ 
    ID_no++;
}

map<const string, const string> Employee::map_this() 
{
    //     How do I do this????
}

1 个答案:

答案 0 :(得分:0)

std::map不是您认为的那样。当您希望将所有员工ID号映射到各自的Employee对象时,将使用映射。

如果您想将两个值作为一个对象返回,那么我建议您使用std::pair

std::pair<const std::string, const std::string> Test::getNameAndId() {
    return {name, employee_ID};
}

然后您可以像std::pair一样访问Employee employee{"Carl"}; auto& p = employee.getNameAndId(); std::cout << "Name: " << p.first << ", Id: " << p.second << std::endl; 中的名称和ID:

Name: Carl, Id: 1

输出:

{{1}}
相关问题