2301_79920703 2024-05-09 22:14 采纳率: 92.6%
浏览 2

>>运算符重载,如何输出?

【问题描述】填空完成 String 对象的输入和输出(输入字符串长度不超过100)
【样例输入】
hello
【样例输出】
hello
(最后一行为string对象,验证没有改变)
↑是问题

部分应该怎么改呀
为什么输入后一直结束不了

↓是我写的代码,只能改变

#include  <iostream>
//#include  <string.h>//特意注释掉的,纯手工实现
using  namespace  std;
class  String  {  
public:
      String()
      {p=NULL;  len=0;}
      String(char *str)
      {p=str;}
      void  display()
      {cout<<p<<endl;}

      //可以改动的部分↓
      friend istream& operator>>(istream& input,String s1)
      {
            char str[100];
            s1.p=new char[100];
            int i=0;
            do
            {
                  cin>>str[i];
                  i++;
            }while (str[i-1]!='\n'&&i<100);
            for(int j=0;j<i;j++)
            {
                  s1.p[j]=str[j];
            }
            s1.p[i]='\0';
            
            return input;    
      }

     friend ostream& operator<<(ostream& output,String&s1)
      {
            cout<<s1.p;
            return output;
      } 
    //可以改动的部分↑
      private:
      char  *p;
      int  len;
};
int  main()  {
    String  string1;
    cin>>string1;
    cout<<string1;

    return  0;
}

  • 写回答

3条回答 默认 最新

  • 专家-皆知 2024-05-09 22:14
    关注

    引自免费微信小程序:皆我百晓生

    在C++中,可以通过重载<<运算符来实现String对象的输出,只需在类中定义一个成员函数,签名如:std::ostream& operator<<(std::ostream&, const YourStringClass&)

    评论

报告相同问题?

问题事件

  • 创建了问题 5月9日

悬赏问题

  • ¥15 from seleniumwire import webdriver 在抓取http://链接的时候会自动转https://这个怎么解决
  • ¥15 hive直连数据库模式插入mysql表数据失败(相关搜索:数据库)
  • ¥30 不会,学习,有偿解答
  • ¥15 SQL查询语句报错(检查)
  • ¥15 此表中公式应该怎么写
  • ¥15 求HI-TECH PICC 9.50 PL3安装包
  • ¥15 下载ctorch报错,求解
  • ¥15 如何入门学习c语言,单片机
  • ¥15 idea 编辑语言的选择
  • ¥15 Windows下部署Asmjit