重载符号的总结

//运算符重载的相关知识点

//重载:一名多用  自定义规则

//不可重载的运算符:    .     ::     .*       ?:      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;

}

/**/

猜你喜欢

转载自blog.csdn.net/ys5858588/article/details/81236749
今日推荐