this指针

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,****编译器编译语句重上到下执行,在同一文件中,要避免循环声明,,可以将代码拆开,先声明,在函数后写定义;

转载于:https://www.cnblogs.com/eemjwu/p/8620272.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值