示例1:重载++运算符:
// CPP program to illustrate// operators that can be overloaded#include <iostream>using namespace std;class overload {private:int count;public:overload(): count(4){}void operator++(){count = count + 1;}void Display(){cout << "Count: " << count;}};int main(){overload i;// this calls "function void operator ++()" function++i;i.Display();return 0;}
输出:
Count:5
当++运算符对重载类的对象(在这种情况下为对象i)进行操作时,将调用此函数。在程序中,定义了void operator ++()运算符功能(在重载类内部)。对于i对象,此函数将count的值增加1。
示例2:重载++运算符和重载postincrement运算符:
#include <iostream>using namespace std;class overload {private:int count;public:overload(int i): count(i){}overload operator++(int){return (count++);}overload operator++(){count = count + 1;return count;}void Display(){cout << "Count: " << count<<endl;}};// Driver codeint main(){overload i(5);overload post(5);overload pre(5);// this calls "function overload operator ++()" functionpre = ++i;cout<<"results of I = ";i.Display();cout<<"results of preincrement = ";pre.Display();// this call "function overload operator ++()"functioni++;//just to show diffi++; // just to show diffpost = i++;cout<<"Results of post increment = ";post.Display();cout<<"And results of i , here we see difference : ";i.Display();return 0;}
输出:
results of I = Count: 6results of preincrement = Count: 6Results of post increment = Count: 8And results of i , here we see difference : Count: 9
示例3:重载this运算符:
#include <iostream>using namespace std;class overload {int a[3];public:overload(int i, int j, int k){a[0] = i;a[1] = j;a[2] = k;}int operator[](int i){return a[i];}};int main(){overload ob(1, 2, 3);cout << ob[1]; // displays 2return (0);}
输出:
2个
**示例4:**重载->运算符:
#include <bits/stdc++.h>using namespace std;class GFG {public:int num;GFG(int j){num = j;}GFG* operator->(void){return this;}};// Driver codeint main(){GFG T(5);GFG* Ptr = &T;// Accessing num normallycout << "T.num = " << T.num << endl;// Accessing num using normal object pointercout << "Ptr->num = " << Ptr->num << endl;// Accessing num using -> operatorcout << "T->num = " << T->num << endl;return 0;}
输出 :
T.num = 5
Ptr-> num = 5
T->num= 5
不能重载的运算符列表
1>范围解析运算符 (::)
2>指针到成员运算符(。*)
3>成员访问权限或点运算符(。)
4>三元或条件运算符(?:)
5>对象大小运算符(sizeof)
6>对象类型运算符(typeid)
示例5:重载此。(dot)运算符
点运算符不能重载,因此会导致错误。
#include <iostream>#include <iostream>class cantover {public:void fun();};class X { // assume that you can overload .cantover* p;cantover& operator.(){return *p;}void fun();};void g(X& x){x.fun(); // X::fun or cantover::fun or error?}
这个问题其实我们可以通过几种方式解决,大家可以自行尝试一下!
以上就是今天的全部内容了。每日分享小知识,希望对你有帮助~
**另外如果你想更好的提升你的编程能力,学好C语言C++编程!**弯道超车,快人一步!笔者这里或许可以帮到你~
编程学习书籍分享:
编程学习视频分享:
C语言C++编程学习交流圈子,**QQ群【981108780】**微信公众号:C语言编程学习基地
分享(源码、项目实战视频、项目笔记,基础入门教程)
欢迎转行和学习编程的伙伴,利用更多的资料学习成长比自己琢磨更快哦!