友元函数和运算符重载

来源:互联网 发布:淘宝旺旺号有什么用 编辑:程序博客网 时间:2024/05/22 04:29
//友元函数/*class A{//友元函数friend void modify_i(A *p, int a);private:int i;public:A(int i){this->i = i;}void myprint(){cout << i << endl;}};//友元函数的实现,在友元函数中可以访问私有的属性void modify_i(A *p, int a){p->i = a;}void main(){A* a = new A(10);a->myprint();modify_i(a,20);a->myprint();system("pause");}*//*//友元类class A{//友元类friend class B;private:int i;public:A(int i){this->i = i;}void myprint(){cout << i << endl;}};class B{public://B这个友元类可以访问A类的任何成员void accessAny(){a.i = 30;}private:A a;};*///运算符重载/*class Point{public:int x;int y;public:Point(int x = 0, int y = 0){this->x = x;this->y = y;}void myprint(){cout << x << "," << y << endl;}};//重载+号Point operator+(Point &p1, Point &p2){Point tmp(p1.x + p2.x, p1.y + p2.y);return tmp;}//重载-号Point operator-(Point &p1, Point &p2){Point tmp(p1.x - p2.x, p1.y - p2.y);return tmp;}void main(){Point p1(10,20);Point p2(20,10);Point p3 = p1 + p2;p3.myprint();system("pause");}*///成员函数,运算符重载/*class Point{public:int x;int y;public:Point(int x = 0, int y = 0){this->x = x;this->y = y;}//成员函数,运算符重载Point operator+(Point &p2){Point tmp(this->x + p2.x, this->y + p2.y);return tmp;}void myprint(){cout << x << "," << y << endl;}};void main(){Point p1(10, 20);Point p2(20, 10);//运算符的重载,本质还是函数调用//p1.operator+(p2)Point p3 = p1 + p2;p3.myprint();system("pause");}*///当属性私有时,通过友元函数完成运算符重载class Point{friend Point operator+(Point &p1, Point &p2);private:int x;int y;public:Point(int x = 0, int y = 0){this->x = x;this->y = y;}void myprint(){cout << x << "," << y << endl;}};Point operator+(Point &p1, Point &p2){Point tmp(p1.x + p2.x, p1.y + p2.y);return tmp;}void main(){Point p1(10, 20);Point p2(20, 10);//运算符的重载,本质还是函数调用//p1.operator+(p2)Point p3 = p1 + p2;p3.myprint();system("pause");}

原创粉丝点击