c++ - Trouble with classes and adding objects -
i having trouble classes. have 3 different classes: store, customer , product. in store class want able add customer. problem way need add customer not follow way customer called in customer.h. have store.h:
void addcustomer(int customerid, string customername); in customer.h have:
customer(); customer(string name, int customerid, bool credit); in customer.cpp have:
customer::customer(string name, int customerid, bool credit) : name(name), customerid(customerid), credit(credit){} and in store.cpp have following:
void store::addcustomer(int customerid, string customername){ bool credit = false; customer addcustomer(int customerid, string customername); customer* customer = new customer(name = "null", customerid = 0, credit); customers.push_back(customer); (int = 0; < customers.size(); ++i) { if (customers.at(i)->getid() == customerid){ throw runtime_error("customer added."); } } } the exception thrown if customer has been added in vector. else works example of , set functions 3 classes 1 block of code wont work , not error program wont run further point. doing wrong?
i dont understand logic of function. if want check if customer in vector, should before add vector, not afterwards. there lots of stuff in code not understand , wonder why dont huge list of compiler errors, method this:
void store::addcustomer(int customerid, string customername){ (int = 0; < customers.size(); ++i) { if (customers.at(i).getid() == customerid){ return; // why runtime error? if customer there // dont add it.... } } customers.push_back(customer(customername,customerid,false)); } note assumed change vector holding pointers holding objects (ie std::vector<customer>). storing pointers in vector never makes sense. not use runtime exception here. runtime exceptions should things not supposed happen.
a runtime excpetion make sense, if made sure before customer added new customer. runtime exception tell there problem code making sure new customer. however, suppose function place check. not exception, can occur during normal program execution. if calling code needs know if customer added or not, make method return bool example.
Comments
Post a Comment