#include <iostream> #include <cstdio> #include <cstring> using namespace std; class STRING{ char* pstr; public: STRING(const char* s="");//已实现 ~STRING();//已实现 friend istream& operator>>(istream& in, STRING& s); friend ostream& operator<<(ostream& os, const STRING& s); }; int main() { STRING s; cin >> s; cout << s << endl; return 0; } /* 请在这里填写答案,,你只需要实现输入输出运算符(>>、<<)的重载即可 */
时间: 2023-06-17 16:05:49 浏览: 49
可以这样实现输入输出运算符的重载:
```c++
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
class STRING{
char* pstr;
public:
STRING(const char* s="");
~STRING();
friend istream& operator>>(istream& in, STRING& s);
friend ostream& operator<<(ostream& os, const STRING& s);
};
STRING::STRING(const char* s) {
pstr = new char[strlen(s)+1];
strcpy(pstr, s);
}
STRING::~STRING() {
delete []pstr;
}
istream& operator>>(istream& in, STRING& s) {
char buffer[1024];
in.getline(buffer, 1024);
s.pstr = new char[strlen(buffer)+1];
strcpy(s.pstr, buffer);
return in;
}
ostream& operator<<(ostream& os, const STRING& s) {
os << s.pstr;
return os;
}
int main() {
STRING s;
cin >> s;
cout << s << endl;
return 0;
}
```
在输入运算符中,我们使用`getline()`函数来读取输入的字符串,然后动态分配空间并将字符串拷贝到对象的数据成员中。
在输出运算符中,我们直接输出对象的数据成员。
注意,在使用动态分配空间时,需要在析构函数中释放空间。
相关推荐

















