关于多种运算符重载的问题,最好多几条注释,解释清楚一点,注意其返回值的不同
4条回答 默认 最新
- 技术专家团-小桥流水 2023-04-09 23:01关注
代码:
#include <iostream> using namespace std; class CStr { private: char* data; int len; public: CStr(const char* d = 0) { //cout << "construct----------" << endl; if (d == 0) { data = 0; len = 0; } else { len = 0; while (d[len] != '\0') len++; data = new char[len + 1];//多申请一个字节给\0 for (int i = 0; i < len; i++) data[i] = d[i]; data[len] = '\0'; //结束符 } } ~CStr() { //cout << "disconstruct....." << endl; //析构函数中不要delete data;否则+运算回得不到结果 } CStr& operator = (CStr& s) { //cout << "=:" << endl; delete[] data; len = s.len; data = new char[len + 1]; for (int i = 0; i < len; i++) data[i] = s.data[i]; data[len] = '\0'; return *this; } CStr operator +(const CStr& a) { //cout << "+" << endl; char* p = new char[len + a.len + 1]; int i = 0; for (; i < len; i++) p[i] = data[i]; for (int j = 0; j < a.len; j++) p[i + j] = a.data[j]; p[len + a.len] = '\0'; CStr t(p); delete[] p; return t; } CStr operator +=(const CStr& a) { this->data = (char*)realloc(this->data, len + a.len + 1); //扩容 for (int j = 0; j < a.len; j++) this->data[len + j] = a.data[j]; this->data[len + a.len] = '\0'; len += a.len; //修正长度 return *this; } bool operator >(const CStr& a) { int t = len > a.len ? a.len : len; for (int i = 0; i < t; i++) { if (data[i] > a.data[i]) return true; } return false; } bool operator <(const CStr& a) { int t = len > a.len ? a.len : len; for (int i = 0; i < t; i++) { if (data[i] < a.data[i]) return true; } return false; } bool operator ==(const CStr& a) { if (len != a.len) return false; for (int i = 0; i < len; i++) { if (data[i] != a.data[i]) return false; } return true; } char operator [](int index) { if (index < len) return data[index]; else return '\0'; } friend ostream& operator <<(ostream& out, const CStr& a) { out << a.data; return out; } }; int main() { char buf[100] = { 0 }; cout << "请输入一个字符串创建CStr 实例a:" << endl; cin >> buf; CStr a(buf); cout << "请输入一个字符串创建CStr 实例b:" << endl; cin >> buf; CStr b(buf); CStr c; c = a; cout << "CStr c=a; c:" << c << endl; CStr d = a + b; cout << "CStr d=a+b; d:" << d << endl; cout << "a>b:" << (a > b) << endl; cout << "请输入要获取的实例a的元素下标:"; int index; cin >> index; cout << "a[" << index << "]=" << a[index] << endl; return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥20 wireshark抓不到vlan
- ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
- ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
- ¥15 stata安慰剂检验作图但是真实值不出现在图上
- ¥15 c程序不知道为什么得不到结果
- ¥40 复杂的限制性的商函数处理
- ¥15 程序不包含适用于入口点的静态Main方法
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来