码迷,mamicode.com
首页 > 编程语言 > 详细

C++(三十三) — 全局函数、成员函数的区别

时间:2019-01-15 14:31:33      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:void   函数的参数   ret   col   变量   个数   +=   函数   cout   

 区别:

(1)全局函数的参数个数,比局部函数要多一个;

(2)二者都可,返回元素、返回引用。

 

class test 
{
public:
    test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    test()
    {
    }
// 成员函数返回一个元素 test testAdd(test
&t2) { test temp(this->a + t2.a, this->b + t2.b); return temp; } // 成员函数,返回一个引用,相当于返回自身 // this = > &t1,所以返回值 *this 相当于返回一个元素 test& testAdd2(test &t2) { this->a += t2.a; this->b += t2.b; return *this; } void print() { cout << "a: " << a << " b: " << b << endl; } private: int a; int b; }; test testAdd(test &t1, test &t2) { test t3; return t3; } void main() { test t1(1, 2); test t2(3, 4); test t3, t4; // 全局函数的方法 t3 = testAdd(t1, t2); // 成员变量的方法 t4 = t1.testAdd(t2); // 匿名对象 复制给 t4 test t5 = t1.testAdd(t2);//匿名对象,直接转换为 t5 t4.print(); t5.print(); system("pause"); return; }

 

C++(三十三) — 全局函数、成员函数的区别

标签:void   函数的参数   ret   col   变量   个数   +=   函数   cout   

原文地址:https://www.cnblogs.com/eilearn/p/10271198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!