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;
cin.get();
return 0;
}
输出效果
通过查看反汇编,发现给+(加号)实现了重载,对+重载其实现是用函数实现
用自定义string,实现字符串拼接
先用add函数,实现字符串拼接
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
class mystr
{
public:
char* str;
int len;
inline mystr() :str(nullptr), len(0)
{
}
mystr(const char* str)
{
this->len = strlen(str) + 1;
this->str = new char[this->len];
strncpy(this->str, str, this->len);
}
mystr(const mystr &mystr)
{
this->len = mystr.len;
this->str = new char[this->len];
strncpy(this->str, mystr.str, this->len);
}
mystr add(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);
strncat(tmp.str, str.str, count - (this->len));
return tmp;
}
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);
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