Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <memory>
- class Item
- {
- std::string name;
- std::weak_ptr<Item> pair;
- public:
- const int size{ 34 };
- Item(std::string nameP) : name{ nameP } { std::cout << "Item created for " << this << '\n'; }
- Item(const Item& it) = delete;
- Item& operator=(const Item& it) = delete;
- const std::string& getName()const { return name; };
- void print()const { std::cout << "Item # " << this << " named " << name << '\n'; }
- ~Item() { std::cout << "Item destroyed for " << this << '\n'; }
- const std::shared_ptr<Item> getPair()const { return pair.lock(); }
- friend bool addPair(std::shared_ptr<Item>& left, std::shared_ptr<Item>& right)
- {
- if (!left or !right)
- {
- return false;
- }
- left->pair = right;
- right->pair = left;
- std::cout << left->getName() << " paired with " << right->getName() << '\n';
- return true;
- }
- friend bool addFriend(std::shared_ptr<Item>& left, std::shared_ptr<Item>& right)
- {
- if (!left or !right)
- {
- return false;
- }
- left->pair = right;
- std::cout << right->getName() << " is friend of " << left->getName() << '\n';
- return true;
- }
- };
- void printItem(Item* it)
- {
- it->print();
- }
- int main()
- {
- std::shared_ptr<Item> it1{ std::make_shared<Item>("Item One") };//[One - 1]
- std::shared_ptr<Item> it2{ std::make_shared<Item>("Item Two") };//[Two - 1]
- addPair(it1, it2); // [One - 1] [Two - 1]
- //addFriend(it1, it2);
- std::cout << std::boolalpha << "One paired with Two: " << (it1 == it2->getPair()) << '\n'; // [One - 2] [Two - 1] -> [One - 1] [Two - 1]
- std::cout << std::boolalpha << "Two paired with One: " << (it2 == it1->getPair()) << '\n'; // [One - 1] [Two - 2] -> [One - 1] [Two - 1]
- auto it1Pair{ it1->getPair() }; //[Two - 2]
- auto it2Pair{ it2->getPair() }; //[One - 2]
- std::cout << "Item One pair is: " << it1Pair->getName() << '\n';
- std::cout << "Item two pair is: " << it2Pair->getName() << '\n';
- //it1->print();
- //it2->print();
- return 0;
- }
- // it2Pair - [One - 1]
- // it1Pair - [Two - 1]
- // it2 [Two - 0 x]
- // it1 [One - 0 x]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement