友元函数和运算符重载

深藏阁楼爱情的钟 2022-06-11 07:08 277阅读 0赞
  1. //友元函数
  2. /*
  3. class A{
  4. //友元函数
  5. friend void modify_i(A *p, int a);
  6. private:
  7. int i;
  8. public:
  9. A(int i){
  10. this->i = i;
  11. }
  12. void myprint(){
  13. cout << i << endl;
  14. }
  15. };
  16. //友元函数的实现,在友元函数中可以访问私有的属性
  17. void modify_i(A *p, int a){
  18. p->i = a;
  19. }
  20. void main(){
  21. A* a = new A(10);
  22. a->myprint();
  23. modify_i(a,20);
  24. a->myprint();
  25. system("pause");
  26. }
  27. */
  28. /*
  29. //友元类
  30. class A{
  31. //友元类
  32. friend class B;
  33. private:
  34. int i;
  35. public:
  36. A(int i){
  37. this->i = i;
  38. }
  39. void myprint(){
  40. cout << i << endl;
  41. }
  42. };
  43. class B{
  44. public:
  45. //B这个友元类可以访问A类的任何成员
  46. void accessAny(){
  47. a.i = 30;
  48. }
  49. private:
  50. A a;
  51. };
  52. */
  53. //运算符重载
  54. /*
  55. class Point{
  56. public:
  57. int x;
  58. int y;
  59. public:
  60. Point(int x = 0, int y = 0){
  61. this->x = x;
  62. this->y = y;
  63. }
  64. void myprint(){
  65. cout << x << "," << y << endl;
  66. }
  67. };
  68. //重载+号
  69. Point operator+(Point &p1, Point &p2){
  70. Point tmp(p1.x + p2.x, p1.y + p2.y);
  71. return tmp;
  72. }
  73. //重载-号
  74. Point operator-(Point &p1, Point &p2){
  75. Point tmp(p1.x - p2.x, p1.y - p2.y);
  76. return tmp;
  77. }
  78. void main(){
  79. Point p1(10,20);
  80. Point p2(20,10);
  81. Point p3 = p1 + p2;
  82. p3.myprint();
  83. system("pause");
  84. }
  85. */
  86. //成员函数,运算符重载
  87. /*
  88. class Point{
  89. public:
  90. int x;
  91. int y;
  92. public:
  93. Point(int x = 0, int y = 0){
  94. this->x = x;
  95. this->y = y;
  96. }
  97. //成员函数,运算符重载
  98. Point operator+(Point &p2){
  99. Point tmp(this->x + p2.x, this->y + p2.y);
  100. return tmp;
  101. }
  102. void myprint(){
  103. cout << x << "," << y << endl;
  104. }
  105. };
  106. void main(){
  107. Point p1(10, 20);
  108. Point p2(20, 10);
  109. //运算符的重载,本质还是函数调用
  110. //p1.operator+(p2)
  111. Point p3 = p1 + p2;
  112. p3.myprint();
  113. system("pause");
  114. }
  115. */
  116. //当属性私有时,通过友元函数完成运算符重载
  117. class Point{
  118. friend Point operator+(Point &p1, Point &p2);
  119. private:
  120. int x;
  121. int y;
  122. public:
  123. Point(int x = 0, int y = 0){
  124. this->x = x;
  125. this->y = y;
  126. }
  127. void myprint(){
  128. cout << x << "," << y << endl;
  129. }
  130. };
  131. Point operator+(Point &p1, Point &p2){
  132. Point tmp(p1.x + p2.x, p1.y + p2.y);
  133. return tmp;
  134. }
  135. void main(){
  136. Point p1(10, 20);
  137. Point p2(20, 10);
  138. //运算符的重载,本质还是函数调用
  139. //p1.operator+(p2)
  140. Point p3 = p1 + p2;
  141. p3.myprint();
  142. system("pause");
  143. }

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读