(C++)类内运算符重载时:此运算符函数的参数太多/少
生活随笔
收集整理的這篇文章主要介紹了
(C++)类内运算符重载时:此运算符函数的参数太多/少
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注意:類內運算符重載時只能有且僅有一個參數;類內其他函數可以有多個參數。
如果參數過多:
方法一:利用全局函數類外實現;
方法二:利用友元類內實現
#include <iostream>
using namespace std;
#include <string> class person
{
public:person(int a, int b){m_a = a;m_b = b;}int m_a;int m_b;person &add_person(person& p){this->m_a+=p.m_a ;this->m_b += p.m_b;return *this;}person operator+(person& p) {person temp(0,0);temp.m_a = this->m_a + p.m_a;temp.m_b = this->m_b + p.m_b;return temp;}//方法二:利用友元類內實現//friend ostream& operator<<(ostream& cout, person p);//本質:簡化為cout<<p};//方法一:利用全局函數類外實現;
ostream& operator<<(ostream& cout, person p)//本質:簡化為cout<<p
{cout << "m_a=" << p.m_a << "\tm_b=" << p.m_b;return cout;
}int main()
{person p1(1, 2);person p2(1, 2);person p = p1 + p2;cout << p1<< endl;system("pause");return 0;
}
?
總結
以上是生活随笔為你收集整理的(C++)类内运算符重载时:此运算符函数的参数太多/少的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (Python)石头剪刀布游戏
- 下一篇: 利用标准库sprintf、sscanf函