运载符重载
1、運載符重載的調用形式
《返回形式》operator《運算符》(參數表)
有兩種調用形式:
顯示的調用:a.operator+(b)
隱士的調用: a+b
函數例子:
<span style="font-size:18px;">#include<iostream> using namespace std; class A { private:int n; public:A(int x = 0){n = x;}int getn(){return n;}A operator+(A a); }; A A::operator+(A a) {A temp;temp.n = a.n + n;return temp; }int main() {A ob1(1), ob2(2), ob3, ob4;ob3 = ob1 + ob2;ob4 = ob1.operator+(ob2);cout << "ob3.n" << " "<<ob3.getn() << endl;cout << "ob4.n" <<"\t"<< ob4.getn() << endl;system("pause");return 0; }</span><span style="font-size:18px;">#include<iostream> using namespace std; class A { private:int n; public:A(int x = 0){n = x;}int getn(){return n;}A operator++();}; A A::operator++() {++n;return *this; }int main() {A ob1(1);++ob1;cout << "shuchuzhi" << ob1.getn() << endl;ob1.operator++();cout << "bianhuan" << ob1.getn() << endl;system("pause");return 0; }</span>
2、運算符重載是類的友元函數是
調用格式:
friend <返回類型> operator<運算符>(參數表)
在類外定義
《返回類型》 operator<運算符》(參數表)
友元函數可以調用類的私有成員,相當于類的公有成員
顯示的調用:
operator+(a,b)
隱士的調用:a+b
<span style="font-size:18px;">#include<iostream> using namespace std; class A { private:int a, b; public:A(int x = 0, int y = 0){a = x;b = y;}int geta(){return a;}int getb(){return b;}friend A operator+(A p, A q); }; A operator+(A p, A q) {A temp;temp.a = p.a + q.a;temp.b = p.b + q.b;return temp; } int main() {A ob1(1, 2), ob2(3, 4), ob3, ob4;ob3 = ob1 + ob2;ob4 = operator+(ob1, ob2);cout << ob3.geta() << " " << ob3.getb() << endl;cout << ob4.geta() << " " << ob4.getb() << endl;system("pause");return 0;}</span>總結
- 上一篇: 求n!中含有某个因子个数的方法
- 下一篇: 面向对象的多态性(1)