98.重载的三种方式以及重载符号的交换律

 1 #include "mainwindow.h"
 2 #include <QApplication>
 3 #include <QPushButton>>
 4 
 5 //重载的三种形式,成员函数重载
 6 //友元函数重载,可以使用私有变量以及保护变量
 7 //一般函数重载都是公有变量
 8 
 9 class button
10 {
11     QPushButton *p;
12     int x,y;
13 
14     friend void operator *(button &buttonx,int n);
15     friend void operator *(int n,button &buttonx);
16 public:
17     button():x(500),y(400)
18     {
19         p = new QPushButton;
20         p->resize(x,y);
21         p->show();
22     }
23     ~button()
24     {
25         delete p;
26     }
27     
28     bool operator < (button &buttonx)
29     {
30         return this->x*this->y < buttonx.x*buttonx.y;
31     }
32 };
33 
34 void operator *(button &buttonx,int n)
35 {
36     buttonx.x*=n;
37     buttonx.y*=n;
38     buttonx.p->resize(buttonx.x,buttonx.y);
39 }
40 
41 void operator *(int n,button &buttonx)
42 {
43     buttonx.x*=n;
44     buttonx.y*=n;
45     buttonx.p->resize(buttonx.x,buttonx.y);
46 }
47 
48 //涉及this指针则不可以在友元函数或外部函数中重载
49 //void operator [](button &buttonx)
50 // = [] () ->等这些运算符涉及到this指针,必须不能用友元函数以及外部函数
51 
52 int main(int argc, char *argv[])
53 {
54     QApplication a(argc, argv);
55 
56     button b;
57     2*b;
58 
59     qDebug() << "hello" << endl;
60     return a.exec();
61 }
原文地址:https://www.cnblogs.com/xiaochi/p/8598402.html