Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 4th, 2012  |  syntax: None  |  size: 1.36 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. returning a local as value/reference
  2. #include<iostream>
  3. #include<stdio.h>
  4. #include<string>
  5. using namespace std;
  6. class A
  7. {
  8.     public:
  9.         int x;
  10.         string s;
  11.         A(int xx,string ss):x(xx),s(ss)
  12.     {
  13.         cout<<"A::A()"<<x<<","<<s<<"n";
  14.     }
  15.         A(const A& that)
  16.         {
  17.             cout<<"cpy ctrn";
  18.             x=that.x;
  19.             s=that.s;
  20.         }
  21.         A& operator=(const A& that)
  22.         {
  23.             cout<<"operator=n";
  24.         }
  25.         ~A()
  26.         {
  27.             cout<<"~A()"<<s<<"n";
  28.         }
  29. };
  30.  
  31. const A& getA1()
  32. {
  33.     A a(1,"A1");
  34.     cout<<"returning from A1n";
  35.     return a;
  36. }
  37.  
  38. A& getA2()
  39. {
  40.     A a(2,"A2");
  41.     cout<<"returning from A2n";
  42.     return a;
  43. }
  44.  
  45. A getA3()
  46. {
  47.     A a(3,"A3");
  48.     cout<<"returning from A3n";
  49.     return a;
  50. }
  51.  
  52. int main()
  53. {
  54.     A &newA2 = getA2();       //.....................LINE 2
  55.     cout<<"returned from A2n";
  56.     cout<<"-----------------------------n";
  57.     A newA3 = getA3();       //......................LINE 3
  58.     //A const  newConstA3 = getA3 ();
  59.     cout<<"returned from A3n";
  60.     cout<<"-----------------------------n";
  61.     //cout<<"newA2="<<newA2.x<<","<<newA2.s<<"n";
  62.     cout<<"newA3="<<newA3.x<<","<<newA3.s<<"n";
  63.  
  64. }
  65.        
  66. A::A()2,A2
  67. returning from A2
  68. ~A()A2
  69. returned from A2
  70. -----------------------------
  71. A::A()3,A3
  72. returning from A3
  73. returned from A3
  74. -----------------------------
  75. newA3=3,A3
  76. ~A()A3