C++ 从函数返回对象
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。
相反,您可以将这些存储在 std::map 中,并将 id 作为它们的键......或者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;
}
相关文章:
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 如何访问从 COM 对象返回的 VARIANT 数据类型中的安全数组C++?
- 从我的对象返回静态数组
- 将unique_ptr作为<Object>unique_ptr<常量对象返回>
- 从右值对象返回成员
- 视觉对象 返回 C++ 中的双精度值
- 为什么类型为 sf::Text 的对象返回不同的 getPosition().y 和 getLocalBounds().
- std::min_element 从类对象返回意外结果
- C++无效的对象返回语义
- const引用是否延长临时对象返回的临时对象的寿命
- 将 NULL 作为对象返回时未收到任何警告
- 如何在 C# 中从 com 对象返回数组(double[])
- 从重载运算符返回引用,并使用临时对象返回表达式
- Cin 对象返回值 c++
- 将变量作为类对象返回
- 使用可更改对象返回只读的最佳方法是什么
- 如何在Cython中从另一个包装对象返回包装的c++对象
- 当对象返回时,c++动态数组被清除
- 从带有动态字段的函数、对象返回
- 从堆栈上的匿名对象返回对*this的引用