运算符重载

目录

1.两点注意事项:

1.编译器首先到类里面去找运算符重载函数,然后再到全局下寻找重载函数。

2.友元关系是单向的。

2.运算符重载的代码实现:

3.string的几种用法

1.string是在内部定义的字符串类,重载了许多常用的运算符,常用操作如下:

2.迭代器遍历string


1.两点注意事项:

1.编译器首先到类里面去找运算符重载函数,然后再到全局下寻找重载函数。

2.友元关系是单向的。

2.运算符重载的代码实现:

class CComplex
{
public:
	CComplex(int a = 10, int b = 10) :real(a), mima(b)
	{
		cout << "complex" << endl;
	}
	~CComplex() 
	{
		cout << "~complex" << endl;
	}
	CComplex(const CComplex &src) :real(src.real), mima(src.mima)
	{
		cout << "CComplex const " << endl;
	}
	/*CComplex operator+ (const CComplex &src)
	{
		cout << "operator+ " << endl;
		return CComplex(real + src.real, mima + src.mima);
		
	}*/
	void operator+=(const CComplex &src)
	{
		real += src.real;
		mima += src.mima;
	}
	CComplex& operator++(int)//后置
	{
		real++; 
		mima++;
		return *this;
	}
	CComplex& operator++()//前置
	{
		++real;
		++mima;
		return *this;
	}
	friend ostream&  operator<<(ostream&out, const CComplex &src);//有元关系是单向得
	friend istream& operator>>(istream&in,  CComplex &src);
	friend CComplex operator+(const CComplex &src1, const CComplex &src2);
private:
	int real;
	int mima;
};

ostream& operator<<(ostream&out, const CComplex &src)//类外定义 全局
{
	out << src.mima << "  " << src.real << endl;
	return out;
}
istream& operator>>(istream&in,  CComplex &src)//类外定义 
{
	in >> src.real >> src.mima;
	return in;
}
CComplex operator+(const CComplex &src1, const CComplex &src2)//两边得参数都可以默认得进行隐式生成
{
	//c1 = c3 + 10;//c3.operator+(10)  隐式生成临时对象
	//c1 = 10 + c3;
	return CComplex(src1.real + src2.real, src1.mima + src2.mima);

}

3.string的几种用法

1.string是在内部定义的字符串类,重载了许多常用的运算符,常用操作如下:

string str1 = "aaa";
string str2 = str1;
string str3;
str3 = str2;
string str4 = str1 + str3;
str4 = str1 + "dsadsa";
str4 =  "dsadsa" +str1;
cout << str4 << endl;

更为详细的操作参考网站:https://wenku.baidu.com/view/e3d74e15866fb84ae45c8da0.html

2.迭代器遍历string类。

string s1 = "dsadasdsadsadsadas";
string::iterator it = s1.begin();
for (; it != s1.end(); ++it)
{
	cout << *it << ends;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值