目录
1.编译器首先到类里面去找运算符重载函数,然后再到全局下寻找重载函数。
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;
}