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

一、把全局函數轉化成成員函數,經過this指針隱藏左操做數ios

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

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

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

三、函數返回元素和返回引用this

案例一:實現兩個test相加spa

利用全局函數實現兩個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相加:code

#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; }

案例三:連加等blog

#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; }
相關文章
相關標籤/搜索