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

28 篇文章 0 订阅
本文介绍了Linux下C++的运算符重载基础知识,包括运算符重载的概念,如何重载输出运算符以及单目运算符的重载方法。
摘要由CSDN通过智能技术生成

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值