类和对象(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; }