7-26复习重载并实现重载部分符号
//運算符重載的相關知識點
//重載:一名多用 ?自定義規則
//不可重載的運算符: ? ?. ? ? :: ? ? .* ? ? ? ?: ? ? ?sizeof
//重載后的優先級不變 不改變結合性和所需操作數 ?不去創建新的運算符
?
//<< >>只能用全局函數重載
?
//= , 【】 , () , -> ,只能用成員函數重載
?
//c++通過一個站位參數 ? ?區分前置后置
?
/*
//我們試著重載一下運算符 + 號
#include <iostream>
#include <windows.h>
?
using namespace std;
?
class Complex
{
friend Complex operator +(Complex &c1, Complex &c2);
private:
int m_a;
int m_b;
public:
Complex();
Complex(int a, int b);
void print();
};
?
Complex::Complex()
{
m_a = 0;
m_b = 0;
}
?
Complex::Complex(int a, int b)
{
m_a = a;
m_b = b;
}
?
Complex operator +(Complex &c1, Complex &c2)
{
Complex tmp;
tmp.m_a = c1.m_a + c2.m_a;
tmp.m_b = c1.m_b + c2.m_b;
return tmp;
}
?
void Complex::print()
{
cout << "m_a = " << m_a << " ?m_b = " << m_b << endl;
}
?
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3;
?
c3 = c1 + c2;
c3.print();
?
system("pause");
return 0;
}
*/
?
?
/*
//重載<<
?
#include <iostream>
#include <windows.h>
?
using namespace std;
?
class Complex
{
friend ostream & operator <<(ostream &out, Complex &c);
private:
int m_a;
int m_b;
public:
Complex();
Complex(int a, int b);
void print();
};
?
Complex::Complex()
{
m_a = 0;
m_b = 0;
}
?
Complex::Complex(int a, int b)
{
m_a = a;
m_b = b;
}
?
void Complex::print()
{
cout << "m_a = " << m_a << " ?m_b = " << m_b << endl;
}
?
ostream & operator << (ostream &out, Complex & c)//重載<<
{
out << "c.m_a = " << c.m_a << " ?c.m_b = " << c.m_b << endl;
return out;
}
?
int main()
{
Complex c2(3, 4);
cout << c2 << endl;
?
system("pause");
return 0;
}
?
?
*/
?
/**/
//我們試著重載一下運算符 ++ 前置和后置
#include?<iostream>
#include?<windows.h>
?
using?namespace?std;
?
class?Complex
{
friend?ostream?& operator <<(ostream?&out, Complex?&c);
private:
int?m_a;
int?m_b;
public:
Complex();
Complex(int?a, int?b);
void?print();
Complex?operator + (Complex& c2);
Complex?operator ++(int);//后置++
Complex?&operator ++();//前置++
};
?
Complex::Complex()
{
m_a = 0;
m_b = 0;
}
?
Complex::Complex(int?a, int?b)
{
m_a = a;
m_b = b;
}
?
void?Complex::print()
{
cout << "m_a = "?<< m_a << " ?m_b = "?<< m_b << endl;
}
?
ostream?& operator << (ostream?&out, Complex?& c)//重載 <<
{
out?<< "c.m_a ="?<< c.m_a << " ?c.m_b ="?<< c.m_b << endl;
return?out;
}
?
Complex?Complex::operator ++(int)//后置++
{
Complex?c7;
c7.m_a = m_a;
c7.m_b = m_b;
?
m_a++;
m_b++;
return?c7;
}
?
Complex& Complex::operator ++()//前置++
{
m_a++;
m_b++;
return?*this;
}
?
int?main()
{
Complex?c1(1, 2);
cout << ++c1 << endl;
cout << c1++ << endl;
system("pause");
return?0;
}
/**/
總結
以上是生活随笔為你收集整理的7-26复习重载并实现重载部分符号的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7-25日牛客网刷题 未知点、错题 集合
- 下一篇: 7-26晚上实现mystring