C++ 从函数返回对象

c++ returning object from function?

本文关键字:对象 返回 函数 C++      更新时间:2023-10-16
绝对

的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更好,如果你真的关心性能。

假设您在类CustomergetCustId()公共成员函数:

Customer & Store::getCustomer(unsigned int custId){
    auto custIt = find_if(customerBase.begin(), customerBase.end(), 
        [custId](const Customer& c){ return c.getCustId() == custId });
    return *custIt;
}