Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. // Example program
  2. #include <iostream>
  3. #include <string>
  4. #include <algorithm>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. class T1
  10. {
  11.     public:
  12.     int v;
  13.    
  14.     T1() : v(0){ log("T1 ctr1"); }
  15.     T1(int p) : v(p) { log("T1 ctr2"); }
  16.     ~T1() {log("T1 destr");}
  17.     T1(const T1& other) : v(other.v) { log("T1 copy ctr"); }
  18.     T1& operator=(const T1& other) { cout << "object: " << (long)(this) << " " << "T1 assign op2, other " << (long)(&other) << endl; v = other.v; return *this; }
  19.  
  20.    void log(const string s) { cout << "object: " << (long)(this) << " " << s << endl; }  
  21. };
  22.  
  23. class T2
  24. {
  25.     public:
  26.     T1* v;
  27.     //vector<T1*> v; // uncomment for initializer_list case
  28.    
  29.     T2() : v(0){ log("T2 ctr1"); }
  30.     T2(T1* p) : v(p)  // wont work for vector
  31.     {
  32.         log("T2 ctr2");
  33.         //v.push_back(p); // uncomment for initializer_list case
  34.     }
  35.     /*
  36.     T2(initializer_list<T1*> list) //: v(list) // will work for vector
  37.     {
  38.         log("T2 ctr3");
  39.         //  v = list[0];        // wont work for single variable
  40.         //  v = list.begin();   // wont work either
  41.         v.resize(list.size()); copy(list.begin(), list.end(), v.begin()); // will work for vector too
  42.     }
  43.     */
  44.     ~T2() {log("T2 destr");}
  45.     T2(const T2& other) : v(other.v) { log("T2 copy ctr"); }
  46.     T2& operator=(const T2& other) { cout << "object: " << (long)(this) << " " << "T1 assign op2, other " << (long)(&other) << endl; v = other.v; return *this; }
  47.    
  48.     void log(const string s) { cout << "object: " << (long)(this) << " " << s << endl; }  
  49. };
  50.  
  51. int main()
  52. {
  53.     cout << "test1\n";
  54.     T1* t1 = new T1();
  55.    
  56.     cout << "test2\n";
  57.     T1* t2 = new T1(3);
  58.  
  59.     cout << "test2.1\n";
  60.     T1* t21 = new T1(33);
  61.     *t21 = *t2;
  62.  
  63.     cout << "test3\n";
  64.     T2* t3 = new T2();
  65.  
  66.     cout << "test4\n";
  67.     T2* t4 = new T2( new T1() );
  68.  
  69.     cout << "test5\n";
  70.     T2* t5 = new T2{ new T1(333) };
  71.     //cout << t5->v[0]->v << endl; // test for initializer_list case
  72.    
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement