原创 linux下c++ lesson12 运算符重载基础

1-运算符重载概念.cpp#include iostreamusing namespace std;class Complex{//friend Complex operator+(const Complex c1, const Complex c2);private:int a; //实部int b; //虚部public:Complex(int...

1-运算符重载概念.cpp

#include <iostream>

using namespace std;

class Complex
{
	//friend Complex operator+(const Complex &c1, const Complex &c2);
private:
	int a;    //实部
	int b;    //虚部
public:
	Complex(int _a, int _b)
	{
		this->a = _a;
		this->b = _b;
	}

	void print()
	{
		cout << a << " + " << b << "i" << endl;
	}

	Complex operator+(const Complex &c)
	{
		Complex t(0, 0);
		t.a = this->a + c.a;
		t.b = this->b + c.b;

		return t;
	}
};

//运算符重载本质就是函数的重载
/*Complex operator+(const Complex &c1, const Complex &c2)
{
	Complex t(0, 0);
	t.a = c1.a + c2.a;
	t.b = c1.b + c2.b;

	return t;
}*/

int main()
{
	Complex c1(1, 2);
	Complex c2(2, 3);

	c1.print();

	//c1 + c2;
	Complex t(0, 0);
	//t = operator+(c1, c2);
	t = c1 + c2;    //编译器会转换成  t = c1.operator+(c2)
	t.print();

	return 0;
}

2-重载输出运算符.cpp

#include <iostream>

using namespace std;

class Complex
{
	//friend Complex operator+(const Complex &c1, const Complex &c2);
	friend ostream &operator<<(ostream &out, const Complex &c);
private:
	int a;    //实部
	int b;    //虚部
public:
	Complex(int _a, int _b)
	{
		this->a = _a;
		this->b = _b;
	}

	void print()
	{
		cout << a << " + " << b << "i" << endl;
	}

	/*ostream &operator<<(ostream &out)     //如果左操作数不能修改,则不能重载成成员函数
	{
		out << this->a << " + " << b << "i";
		return out;
	}*/
};

//运算符重载本质就是函数的重载
/*Complex operator+(const Complex &c1, const Complex &c2)
{
	Complex t(0, 0);
	t.a = c1.a + c2.a;
	t.b = c1.b + c2.b;

	return t;
}*/

ostream &operator<<(ostream &out, const Complex &c)
{
	out << c.a << " + " << c.b << "i";
	return out;
}

int main()
{
	Complex c1(1, 2);
	c1.print();

	cout << c1 << endl;    //operator<<(operator<<(cout, c1), endl);   等价于 cout.operator<<(c1)

	return 0;
}

3-单目运算符重载.cpp

#include <iostream>

using namespace std;

class Complex
{
	friend ostream &operator<<(ostream &out, const Complex &c);
private:
	int a;    //实部
	int b;    //虚部
public:
	Complex(int _a, int _b)
	{
		this->a = _a;
		this->b = _b;
	}
	
	//后置++
	Complex operator++(int)   //通过占位参数来构成函数重载
	{
		Complex t = *this;
		this->a++;
		this->b++;
		return t;
	}

	//前置++
	Complex &operator++()
	{
		this->a++;
		this->b++;

		return *this;
	}
};

ostream &operator<<(ostream &out, const Complex &c)
{
	out << c.a << " + " << c.b << "i";
	return out;
}

int main()
{
	Complex c1(1, 2);

	cout << c1++ << endl;
	cout << ++c1 << endl;

	return 0;
}

本文标题为:原创 linux下c++ lesson12 运算符重载基础

上一篇: C++内存池的实现
下一篇: C++.进程2

基础教程推荐