<<重载函数中str=buf的理解

本文探讨了C++中使用istream从输入流读取字符串的方法,并详细解释了如何通过重载运算符来实现从字符数组到string对象的转换。文章强调了除了string对象之间的赋值运算符外,还需要重载针对char[]的赋值运算符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

istream & operator>>( istream & in, string & str )
{
    char buf[ string::MAX_LENGTH + 1 ];
    in >> buf;
    if( !in.fail( ) )
        str = buf; //如何理解char buf[]赋值给string对象,为什么可以这样赋值呢???
    return in;

}

答案:

需要重载针对char []的赋值运算符。即

需要有这个string& operator= ( const char* s );
有它string& operator= ( const string& str )不够的。

完成 MyString 类的实现,使程序正确运行 #include <iostream> #include <cstring> using namespace std; class MyString { public: // 无参构造函数 MyString(); // 构造函数,传入一个C语言风格字符串 MyString(const char *s); // 拷贝构造函数 MyString(const MyString &s); // 析构函数 ~MyString(); // 将C语言风格的字符串赋值给MyString对象 MyString& operator=(const char *s); // 将一个MyString对象赋值给另一个MyString对象 MyString& operator=(const MyString &s); // 将这个MyString对象与C语言风格的字符串相连 MyString& operator+=(const char *s); // 将这个MyString对象与另一个MyString对象相连 MyString& operator+=(const MyString &s); // 返回下标为pos的字符 char& operator[](int pos); // 返回子串 [pos, pos+count) // 若请求的子串越过字符串的结尾,即count大于size() - pos,则返回的子串为[pos, size()) // 若pos不在字符串的下标范围内,返回空的MyString对象 // 若count == -1,返回子串[pos, size()) MyString substr(int pos = 0, int count = -1); // 字符串的长度 int size() const; // 返回C语言风格的字符串 const char* c_str() const; private: char *m_buf; int m_size; }; // 请在此处填写 int main() { char s[101]; cin.getline(s, 101); int pos, count; // 创建、拷贝、赋值 MyString s1(s), s2(s1), s3, s4, s5; s3 = s; s4 = s1; cout << "s1: " << s1.c_str() << endl; cout << "s2: " << s2.c_str() << endl; cout << "s3: " << s3.c_str() << endl; cout << "s4: " << s4.c_str() << endl; // 拼接 s3 += s; s4 += s1; cout << "s3 += s: " << s3.c_str() << endl; cout << "s4 += s1: " << s4.c_str() << endl; // 下标 cin >> pos; s4[pos] = 'm'; cout << "s4[pos] = 'm': " << s4.c_str() << endl; // 取子串 cin >> pos >> count; s5 = s4.substr(pos, count); cout << "s5: " << s5.c_str() << endl; // 以后还可以重载<<直接输出一个MyString对象哦 TODO return 0; }
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值