2017-02-22 69 views
-1

我是新来的C++,并且在编写该函数的代码时遇到了麻烦。我只是需要它将ID,名称,产品描述,价格和数量等产品价值存储到矢量库存中。如何为此addProduct函数编写implmentation代码

Store.hpp

#ifndef STORE_HPP 

#define STORE_HPP 
class Product; 
class Customer; 
#include<string> 

#include "Customer.hpp" 
#include "Product.hpp" 

class Store 
{ 
private: 
    std::vector<Product*> inventory; 
    std::vector<Customer*> members; 

public: 
    void addProduct(Product* p); 
    void addMember(Customer* c); 
    Product* getProductFromID(std::string); 
    Customer* getMemberFromID(std::string); 
    void productSearch(std::string str); 
    void addProductToMemberCart(std::string pID, std::string mID); 
    void checkOutMember(std::string mID); 
}; 

#endif 

我试图把它写这种方式。我知道这是错误的,请帮助我。

在此先感谢

void Store::addProduct(Product* p) 
{ 
    Product* p(std::string id, std::string t, std::string d, double p, int qa); 
    inventory.push_back(p); 
} 
+0

您似乎对什么是指针以及何时使用指针感到困惑。请先清理一下。 'addProduct'成员函数已经接收到一个指向'Product'类的实例的指针,为什么你要使用构造函数,并且你在哪里期待'id'等信息来自哪里? – riodoro1

+0

但我得到一个错误,说[错误]没有匹配函数调用'std :: vector :: push_back(Product *(&)(std :: string,std :: string,std :: string,double,int ))' – user1210000

+0

@ riodoro1请告诉我如何写代码存储在载体 – user1210000

回答

0

您可以用p指针传递一个完整的对象,并将其推到向量,它会看起来是一样的,但没有串Product* p(std::string id, std::string t, std::string d, double p, int qa);你也可以创建你的产品的副本,如果你有一个拷贝构造函数,这种方法是有效的。

void Store::addProduct(Product* p) 
{ 

    Product* copyOfP = new Product(*p); 
    inventory.push_back(copyOfP); 
} 

或者其他没有很好的办法: 无效商店:: addProduct命令(产品* P) {

Product* copyOfP = new Product(p->getId(), p->getT(), p->getD, ...); 
    inventory.push_back(copyOfP); 
} 

如果选择拷贝一个变种 - 不要忘记手动删除它们在Store的析构函数中。

0

您的代码

void Store::addProduct(Product* p) 
{ 
    Product* p(std::string id, std::string t, std::string d, double p, int qa); 
    inventory.push_back(p); 
} 

可能会发出一个警告 - 你已经重新声明形式参数p

线

Product* p(std::string id, std::string t, std::string d, double p, int qa); 

看起来像一个函数声明的东西返回一个指针到Product。你在给函数发送Product指针,所以只需要使用:

void Store::addProduct(Product* p) 
{ 
    inventory.push_back(p); 
} 

您正在尝试的push_back功能p - 不要忽视警告。

+0

谢谢你们的工作 – user1210000