[英]c++ returning object from function?
絕對是C ++(和oop)的新手。
只是想問如何通過將單個id傳遞給getter來從列表(如果存在)中返回對象。
我的代碼如下:
class Customer
{
private:
unsigned int custNo;
std::string name;
std::string address;
/* .. */
}
class Store
{
private:
std::string storeName;
std::list<Customer *> customerBase;
std::list<Product *> productStock;
std::list<Sale*> sales;
public:
Store(std::string storeName); // constructor
std::string getStoreName();
Customer & getCustomer(unsigned int custId); //METHOD IN QUESTION
/*..*/
// Constructor
Customer::Customer(std::string name, std::string address)
{
//ctor
}
//
Customer & Store::getCustomer(unsigned int custId){
}
我知道這可能是一個基本問題。 我仍然非常感謝您的幫助。 提前致謝!
只是想問如何通過將單個id傳遞給getter來從列表(如果存在)中返回對象。
指針是您看到“如果存在”時應該考慮的第一件事。 這是因為在C ++中,對象的唯一表示形式是可選的。 值和引用必須始終存在。 因此,函數的返回類型應該是Customer*
,而不是Customer&
:
Customer* Store::getCustomer(unsigned int custId){
...
}
如果需要通過id
快速檢索,請使用map<int,Customer*>
或unordered_map<int,Customer*>
。 您也可以使用列表來執行此操作,但是搜索將是線性的(即,在最壞的情況下,您將遍歷整個列表)。
說到指針,如果必須存儲指向Customer
對象的指針(假設對象本身存儲在其他容器中),則最好在兩個容器中都使用shared_ptr<Customer>
來簡化資源管理。
您可以執行此操作,但是這樣做很麻煩,因為列表未排序,因此您必須遍歷列表並檢查每個結構的ID是否匹配。
相反,您可以將這些存儲在以id為鍵的std :: map中……或者,如果您真的在乎性能的話,最好使用unordered_map。
假設您在類Customer
具有getCustId()
公共成員函數:
Customer & Store::getCustomer(unsigned int custId){
auto custIt = find_if(customerBase.begin(), customerBase.end(),
[custId](const Customer& c){ return c.getCustId() == custId });
return *custIt;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.