1. 程式人生 > >day04 this指針

day04 this指針

nbsp class [] t對象 OS 全局 一個 一個數 返回

1,在成員函數後面加const修飾的不是函數,修飾的是隱藏的this指針

2,同類之間無私處

異類之間有友元

3,最好不要創建臨時對象

  1 #define  _CRT_SECURE_NO_WARNINGS 
  2 #include <iostream>
  3 
  4 using namespace std;
  5 
  6 class Test
  7 {
  8 public:
  9     Test()
 10     {
 11         this->a = 0;
 12         this->b = 0;
 13     }
 14
15 Test(int a, int b) 16 { 17 this->a = a; 18 this->b = b; 19 } 20 21 void printT() 22 { 23 cout << "a = " << a << ", b = " << b << endl; 24 } 25 26 int getA() 27 { 28 return this->a;
29 } 30 31 int getB() 32 { 33 return this->b; 34 } 35 36 //成員函數 37 Test TestAdd01(Test &t1, Test &t2) 38 { 39 Test temp(t1.getA() + t2.getA(), t1.getB() + t2.getB()); 40 return temp; 41 } 42 43 Test TestAdd02(Test &another)
44 { 45 //Test temp(this->a + another.getA(), this->b + another.getB()); 46 Test temp(this->a + another.a, this->b + another.b); 47 48 return temp; 49 } 50 51 52 void TestAdd03(Test &another) 53 { 54 this->a += another.a; 55 this->b += another.b; 56 } 57 58 59 Test & TestAdd04(Test &another) 60 { 61 this->a += another.a; 62 this->b += another.b; 63 64 //返回自己 65 return *this; 66 }//temp引用 = *this 67 68 private: 69 int a; 70 int b; 71 }; 72 73 //提供一個方法來實現兩個Test對象相加 74 //全局函數 75 Test TestAdd(Test &t1, Test &t2) 76 { 77 Test temp(t1.getA() + t2.getA(), t1.getB() + t2.getB()); 78 79 return temp; 80 }//此時會析構temp 81 82 int main(void) 83 { 84 Test t1(10, 20); 85 Test t2(100, 200); 86 87 Test t3 = TestAdd(t1, t2); //調用了一個全局函數 88 89 t3.printT(); 90 91 Test t4 = t1.TestAdd01(t1, t2); 92 t4.printT(); 93 94 Test t5 = t1.TestAdd02(t2); //創建臨時的開銷 95 96 t5.printT(); 97 98 t1.TestAdd03(t2); 99 t1.printT(); 100 101 (t1.TestAdd04(t2)).printT(); //t1的別名 102 103 return 0; 104 }

其中TestAdd04最優;

4,釋放一個數組內存使用 delete [] ;

5,****編譯器編譯語句重上到下執行,在同一文件中,要避免循環聲明,,可以將代碼拆開,先聲明,在函數後寫定義;

day04 this指針