類和對象(13)—— 全局函數與成員函數


1、把全局函數轉化成成員函數,通過this指針隱藏左操作數

Test add(Test &t1,Test &t2)    ===>Test add(Test &t2) 

2、把成員函數轉換成全局函數,多了一個參數

void printAB() ===>void printAB(Test *pthis)

3、函數返回元素和返回引用

案例一:實現兩個test相加

利用全局函數實現兩個test相加

#include <iostream>
using namespace std;

class Test
{
public:
    Test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }

    void printT()
    {
        cout << "a:" << this->a << ",b:" << this->b << endl;
    }

    int getA()
    {
        return this->a;
    }

    int getB()
    {
        return this->b;
    }
private:
    int a;
    int b;
};

//在全局提供一個兩個test相加的函數
Test TestAdd(Test &t1, Test &t2) { Test temp(t1.getA() + t2.getA(), t1.getB() + t2.getB()); return temp; } int main(void)
{
    Test t1(10, 20);
    Test t2(100, 200);

    Test t3 = TestAdd(t1, t2);
    t3.printT();//a:110,b:220

    return 0;
}

利用成員函數實現兩個test相加:

#include <iostream>
using namespace std;

class Test
{
public:
    Test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }

    void printT()
    {
        cout << "a:" << this->a << ",b:" << this->b << endl;
    }

    int getA()
    {
        return this->a;
    }

    int getB()
    {
        return this->b;
    }

    //用成員方法實現兩個test相加,函數返回元素
    Test TestAdd(Test &another) { Test temp(this->a + another.getA(), this->b + another.getB()); return temp; } private:
    int a;
    int b;
};

int main(void)
{
    Test t1(10, 20);
    Test t2(100, 200);

    Test t3 = t1.TestAdd(t2);
    t3.printT();//a:110,b:220

    return 0;
}

案例二:實現test的+=操作

#include <iostream>
using namespace std;

class Test
{
public:
    Test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }

    void printT()
    {
        cout << "a:" << this->a << ",b:" << this->b << endl;
    }

    int getA()
    {
        return this->a;
    }

    int getB()
    {
        return this->b;
    }
  //+=方法
void TestAddEqual(Test &another) { this->a += another.a; this->b += another.b; }
private: int a; int b; }; int main(void) { Test t1(10, 20); Test t2(100, 200); t1.TestAddEqual(t2); t1.printT(); return 0; }

案例三:連加等

#include <iostream>
using namespace std;

class Test
{
public:
    Test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }

    void printT()
    {
        cout << "a:" << this->a << ",b:" << this->b << endl;
    }

    int getA()
    {
        return this->a;
    }

    int getB()
    {
        return this->b;
    }

    //如果想對一個對象連續調用成員方法,每次都會改變對象本身,成員方法需要返回引用
    Test& TestAddEqual(Test &another)//函數返回引用 { this->a += another.a; this->b += another.b; return *this;//如果想返回一個對象本身,在成員方法中,用*this返回
 } private:
    int a;
    int b;
};

int main(void)
{
    Test t1(10, 20);
    Test t2(100, 200);

    t1.TestAddEqual(t2).TestAddEqual(t2);
    t1.printT();//a:210,b:420

    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM