类和对象(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; }
相关文章
相关标签/搜索