运载符重载
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)