首页 > 编程语言 > 详细

c++全局函数 && 成员函数

时间:2017-02-20 14:01:40      阅读:156      评论:0      收藏:0      [点我收藏+]

 1 #include<iostream>
 2 using namespace std;
 3 class Test {
 4 public:
 5     Test(int a=0, int b=0)
 6     {
 7         this->a = a;
 8         this->b = b;
 9     }
10     Test & add_menber(Test &t2)
11     {
12         this->a += t2.a;
13         this->b += t2.b;
14         return *this;
15     }
16     void printf(Test &t)
17     {
18         cout << "a="<<t.a << "b=" << t.b << endl;
19     }
20     ~Test()
21     {
22         
23     }
24 //private://全局函数如果不是友元函数不能访问私有属性
25     int a;
26     int b;
27 
28 };
29 Test add(Test &t1, Test &t2)
30 {
31     Test temp;
32     temp.a= t1.a + t2.a;
33     temp.b = t1.b + t2.b;
34     return  temp;
35 }
36 int main()
37 {
38     Test t1(1, 2), t2(3, 4), t3;
39     t3 = add(t1, t2);
40     cout << "t3.a="<<t3.a<<"t3.b="<<t3.b << endl;
41 
42     Test t4(100, 100),t5(200,200);
43     t4.printf(t4.add_menber(t5));
44     cout << "hello world!\n";
45     return 0;
46 }

summary:

非静态成员函数有this指针,这样的成员函数实现参数会比全局函数少一个,反之全局函数参数会比非静态成员函数多一个。c++中多使用引用更好。

c++全局函数 && 成员函数

原文:http://www.cnblogs.com/yangguang-it/p/6418935.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!