簡體   English   中英

成員函數C ++初學者

[英]Member Functions C++ beginner

因此,基本上,我正在玩一個簡單的雇員類,該類假定將名稱映射到唯一的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::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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM