肚子饿了233 发表于 2021-5-18 20:07:22

C++之重载运算符问题,救命!!

重载运算符‘+’、‘=’与‘-’用于字符串的连接,其中main函数为:

        void main()

        {

             string s1("湖北大学         "),s3;

             string s2("计算机与信息工程学院欢迎您!");

             s3=s1+s2;

             s3.display();

                s3=s1-s2;

             s3.display();



        }

要求运行结果为:

湖北大学         计算机学院欢迎您!

湖北大学计算机学院欢迎您!


我发现了很矛盾的地方,题目中主函数用string作为类名,可是用#include<string>又很矛盾,反正编译器一直报错
有没有大佬愿意补全代码,必定十分感激!

ponyo123 发表于 2021-5-19 14:01:01

本帖最后由 ponyo123 于 2021-5-19 14:04 编辑

#include <iostream>
#include <string>
using namespace std;
class String
{
    private:
    string s;
    public:
    String(string);
    String operator+(const String &b);
    String operator-(const String &a);
    void operator=(const String &b)
    {
      this->s=b.s;
    }
    void display();
};
String::String(string x)
{
    s=x;
}
int main()
{
    String s1("湖北大学   ");
    String s2("计算机与信息工程学院欢迎您!");
        String s4("   ");
    String s3=s1+s2;
    s3.display();
    s3=s3-s4;
    s3.display();
    return 0;
}

String String::operator+(const String &b)
{
    String c=b;
        c.s.insert(0,this->s);                                 //使用insert函数在位置0前插入字符串s
    return c;
}
String String::operator-(const String &a)
{
        for(int i=0;i<this->s.length();i++)
        {
                for(int j=0;j<a.s.length();j++)
                {
                        if(this->s==a.s)
                        {
                                this->s.erase(i,a.s.length());         //使用erase函数从i位置开始删除某长度的字符串
                                i+=a.s.length();
                        }
                }
        }
                return s;
}
void String::display()
{
    cout<<s<<endl;
}

肚子饿了233 发表于 2021-5-19 20:08:43

本帖最后由 肚子饿了233 于 2021-5-19 20:10 编辑

ponyo123 发表于 2021-5-19 14:01
#include
#include
using namespace std;

允许我指正一下:if(this->s==a.s)应改为if(this->s==a.s),s后面的方括号咋打不出来了呢?
页: [1]
查看完整版本: C++之重载运算符问题,救命!!