Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <cassert>
- #include <stdexcept>
- using namespace std;
- class Item {
- private:
- int id;
- static int lastId;
- static int aliveObjects;
- string name;
- double price;
- int amount;
- public:
- Item(string name, double price){
- init(name, price, 1);
- }
- Item(string name, double price, int amount){
- init(name, price, amount);
- }
- ~Item(){
- --aliveObjects;
- }
- private:
- void init(string name, double price, int amount){
- ++aliveObjects;
- setId();
- setName(name);
- setPrice(price);
- setAmount(amount);
- }
- public:
- static int getAliveObjects(){
- return aliveObjects;
- }
- private:
- void setId(){
- this->id = lastId++;
- }
- public:
- int getId(){
- return id;
- }
- private:
- void setName(string name){
- this->name = name;
- }
- public:
- string getName() {
- return name;
- }
- void setPrice(double price){
- if (price >= 0){
- this->price = price;
- } else {
- throw invalid_argument("Price cannot be negative");
- }
- }
- double getPrice(){
- return price;
- }
- void setAmount(int amount){
- if (amount >= 0){
- this->amount = amount;
- } else {
- throw invalid_argument("Amount cannot be negative");
- }
- }
- int getAmount(){
- return amount;
- }
- string toString(){
- stringstream ss;
- ss << getId() << " " << getName() << " " << getPrice() << " " << getAmount();
- return ss.str();
- }
- };
- int Item::lastId = 0;
- int Item::aliveObjects = 0;
- class ItemHandler {
- private:
- Item *item;
- public:
- ItemHandler(Item *item){
- this->item = item;
- }
- Item * get(){
- return this->item;
- }
- ~ItemHandler(){
- delete item;
- }
- };
- int main(){
- try {
- ItemHandler ih(new Item("Chocolate", 1.0));
- cout << ih.get()->toString() << endl;
- Item item1("Chocolate", 1.0);
- item1.setPrice(-1);
- cout << item1.toString() << endl;
- } catch(exception &e){
- cout << e.what() << endl;
- } catch(...){
- cout << "Unexpected error" << endl;
- }
- assert(Item::getAliveObjects() == 0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement