c++ 操作符重载
c++操作符重载,来类型string来说
#include <iostream>
#include <string>
using namespace std;
//操作符+重载
int main(int argc, char *argv[])
{
string str1 = "hello ";
string str2 = "world";
cout << str1 + str2 << endl; //两个类型string对象,如何实现字符串拼接呢?
cin.get();
return 0;
}
输出效果

通过查看反汇编,发现给+(加号)实现了重载,对+重载其实现是用函数实现
用自定义string,实现字符串拼接
先用add函数,实现字符串拼接#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
//封装mystr,实现拼接字符串
class mystr
{
public:
char* str;
int len;
inline mystr() :str(nullptr), len(0) //5.无参构造,默认初始化str和len
{
}
mystr(const char* str) //1.通过构造函数,将字符串拷贝内部str上
{
this->len = strlen(str) + 1;
this->str = new char[this->len];
strncpy(this->str, str, this->len);
}
mystr(const mystr &mystr) //5. 通过拷贝构造函数,返回一个引用
{
this->len = mystr.len;
this->str = new char[this->len];
strncpy(this->str, mystr.str, this->len);
}
mystr add(const mystr &str) //2.接收一个mystr类型变量,实现字符串拼接
{
int count = this->len + str.len - 1;
mystr tmp; //3. 调用无参构造函数
tmp.len = count;
tmp.str = new char[count];
strncpy(tmp.str, this->str, this->len); //将当前对象字符串拷贝tmp中
strncat(tmp.str, str.str, count - (this->len));
return tmp; //4. 调用拷贝构造函数
}
//对+实现重载,
mystr operator +(const mystr &str)
{
int count = this->len + str.len - 1;
mystr tmp;
tmp.len = count;
tmp.str = new char[count];
strncpy(tmp.str, this->str, this->len); //将当前对象字符串拷贝tmp中
strncat(tmp.str, str.str, count - (this->len));
return tmp;
}
};
int main(int argc, char *argv[])
{
mystr str1("hello ");
mystr str2("world");
mystr str3 = str1.add(str2); //先用add函数,实现字符串拼接
cout << "add:" << str3.str << endl;
mystr str5 = str1 + str2; //调用重载+操作符,实现字符串拼接
cout << str5.str << endl;
cin.get();
return 0;
}
重载操作符 注意事项
- 不改变操作符优先级
- 不改变操作符的结合性
- 不改变操作符所需的操作数
- 不可以创建新操作符
- 不能重载的操作符 . :: .* ?: sizeof
秋风
2018-03-27