Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <thread>
- using namespace std;
- class Pet {
- public:
- Pet() : Pet("Unnamed", 0) {
- cout << "Pet default constructor" << endl;
- }
- Pet(string name, int age) : mName(name), mBirthTime(time(NULL) - age) {
- }
- Pet(const Pet& p) {
- mBirthTime = time(NULL);
- mName = p.getName() + " child";
- cout << "Pet copy constructor" << endl;
- }
- string &getName() const {
- return mName;
- }
- void setName(string name) {
- mName = name;
- }
- int age() {
- return time(NULL) - mBirthTime;
- }
- void printDossier() {
- cout << "\tName: " << mName << endl
- << "\tBirth Day: " << asctime(localtime(&mBirthTime)) << endl;
- }
- void sendTo(int lon, int lat, function<void(int, Pet*)> callback) {
- mCallbackGo = callback;
- // start in new thread
- mThread = new thread( [&] {
- startGoTo(lon, lat);
- });
- }
- void startGoTo(int lon, int lat) {
- // TODO
- this_thread::sleep_for(chrono::seconds(3)); // simulate long process
- int status = rand();
- if (mCallbackGo) mCallbackGo(status, this);
- }
- ~Pet() {
- cout << "Pet destructor" << endl;
- if (mThread) delete mThread;
- }
- private:
- string mName;
- time_t mBirthTime;
- function<void(int, Pet*)> mCallbackGo = nullptr;
- thread *mThread = nullptr;
- };
- int main()
- {
- Pet pet;
- Pet pet2 = pet;
- pet2.setName("NewName");
- pet.sendTo(3, 4, [] {
- cout << endl <<"Pet " << p->getName() << " finished "
- << "with status " << status << endl << endl;
- });
- this_thread::sleep_for(chrono::seconds(5));
- cout << "Pet 1:" << endl;
- pet.printDossier();
- cout << endl << endl;
- cout << "Pet 2:" << endl;
- pet2.printDossier();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement