成员函数重载:类中的成员函数与前面介绍的普通函数一样,成员函数可以带有缺省的参数,也可以重载成员函数。重载时,函数的形参必须在类型或数目上不同。
缺省函数的成员函数
定义类的指针及如何用指针来引用对象
定义类的数组及数组中元素的引用
#include<iostream> using namespace std; class Ctest { int x,y; int m,n; public: void setxy(int a,int b) { x = a; y = b; } void setxy(int a,int b,int c,int d) { x = a;y = b;m = c; n = d; } void dispxymn(int x) { cout<< x <<","<< y <<","<< m <<"," << n << endl<<endl; } void dispxymn() { cout<< x <<","<< y <<","<< m <<"," << n << endl<<endl; } }; int main() { Ctest obj1,obj2; //参数不同 obj1.setxy(10,20); obj2.setxy(10,20,30,40); //参数 类型不同 obj1.setxy(666); obj2.setxymn(); return 0; }
指针引用对象:
//指针引用对象 #include<iostream> using namespace std; class Ctest { public : double sum() { return x+y; } void setxy(double a,double b) { x = a; y = b; } void dispxy() { cout <<"x="<<x<<","<<"y="<<y<<endl<<endl; } private: int x,y; }; int main() { Ctest obj1,obj2; //定义对象 Ctest *pobj; //对象类的指针(对象指针) pobj = &obj1; pobj->setxy(3.4,6.6); //通过指针引用对象的成员函数 pobj->dispxy(); cout<<"x+y"<<pobj->sum()<<endl; return 0; }
this指针: 不同对象占据内存中的不同区域,他们所保存的数据各不相同,但对成员数据进行操作的成员函数的程序代码是一样的。
当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,然后调用成员函数,每次成员函数存取数据成员时,也隐含使用this指针。
#include<iostream> using namespace std ; class Ctest { private: int x; public: int getx()const { return x; } void setx(int x) { this->x = x; cout <<"this指针存储的内存地址为:"<<this<<endl<<endl; } }; int main() { Ctest obj; //创建一个对象 obj.setx(666); cout<<"对象obj在内存的地址为:"<< &obj <<endl; cout <<"对象obj所保存的值为:"<< obj.getx() << endl; cout <<endl; return 0; }