【问题标题】:Member Functions C++ beginner成员函数 C++ 初学者
【发布时间】:2013-10-26 02:28:30
【问题描述】:

所以基本上我正在玩弄一个简单的员工类,它假设将一个名称映射到一个唯一的 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????
}

【问题讨论】:

  • 您要返回std::pair 还是std::map?地图在这里不会是矫枉过正吗?映射通常用于管理许多对象的类中,而这是您希望在单个函数调用中返回的每个对象的数据。
  • 地图数据成员在哪里?
  • @0x499602D2:不管他要map还是pair,有没有对应的数据成员都无所谓,可以动态创建。
  • 考虑使用std::tuple 或类似的东西,将idname 一起保存,并使用map_this 函数返回它们。 std::map 旨在存储许多键->值对,而不是一个。

标签: c++ class member-functions


【解决方案1】:

std::map 不是你想象的那样。例如,当您想要将所有员工 ID 号映射到它们各自的 Employee 对象时,可以使用映射。

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

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

然后您可以像这样访问std::pair 中的名称和ID:

Employee employee{"Carl"};
auto& p = employee.getNameAndId();
std::cout << "Name: " << p.first << ", Id: " << p.second << std::endl;

输出:

Name: Carl, Id: 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多