[英]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.