Advertisement
Guest User

Untitled

a guest
May 21st, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <functional>
  3. #include <thread>
  4.  
  5. using namespace std;
  6.  
  7. class Pet {
  8.  
  9. public:
  10.     Pet() : Pet("Unnamed", 0) {
  11.         cout << "Pet default constructor" << endl;
  12.     }
  13.  
  14.     Pet(string name, int age) : mName(name), mBirthTime(time(NULL) - age) {
  15.     }
  16.  
  17.     Pet(const Pet& p) {
  18.         mBirthTime = time(NULL);
  19.         mName = p.getName() + " child";
  20.         cout << "Pet copy constructor" << endl;
  21.     }
  22.  
  23.     string &getName() const {
  24.         return mName;
  25.     }
  26.  
  27.     void setName(string name) {
  28.         mName = name;
  29.     }
  30.  
  31.     int age() {
  32.         return time(NULL) - mBirthTime;
  33.     }
  34.  
  35.     void printDossier() {
  36.         cout << "\tName: " << mName << endl
  37.              << "\tBirth Day: " << asctime(localtime(&mBirthTime)) << endl;
  38.     }
  39.  
  40.     void sendTo(int lon, int lat, function<void(int, Pet*)> callback) {
  41.         mCallbackGo = callback;
  42.         // start in new thread
  43.         mThread = new thread( [&] {
  44.             startGoTo(lon, lat);
  45.         });
  46.     }
  47.  
  48.     void startGoTo(int lon, int lat) {
  49.         // TODO
  50.         this_thread::sleep_for(chrono::seconds(3)); // simulate long process
  51.         int status = rand();
  52.         if (mCallbackGo) mCallbackGo(status, this);
  53.     }
  54.  
  55.     ~Pet() {
  56.         cout << "Pet destructor" << endl;
  57.         if (mThread) delete mThread;
  58.     }
  59.  
  60. private:
  61.     string mName;
  62.     time_t mBirthTime;
  63.     function<void(int, Pet*)> mCallbackGo = nullptr;
  64.     thread *mThread = nullptr;
  65. };
  66.  
  67. int main()
  68. {
  69.     Pet pet;
  70.     Pet pet2 = pet;
  71.     pet2.setName("NewName");
  72.  
  73.     pet.sendTo(3, 4, [] {
  74.         cout << endl <<"Pet " << p->getName() << " finished "
  75.              << "with status " << status << endl << endl;
  76.     });
  77.  
  78.     this_thread::sleep_for(chrono::seconds(5));
  79.  
  80.     cout << "Pet 1:" << endl;
  81.     pet.printDossier();
  82.     cout << endl << endl;
  83.  
  84.     cout << "Pet 2:" << endl;
  85.     pet2.printDossier();
  86.  
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement