春风吹又生.c 2023-04-30 11:32 采纳率: 54.8%
浏览 24
已结题

为什么要用const和static来修饰。

1、为什么重载函数里面的形参要用const修饰,有什么用?不加会影响什么?
2、重载输入运算符时,为什么要把str数组定义为static,如果没定义为static就会出现乱码,这是为什么?


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;

class mystring
{
public:
    mystring() {}   //无参构造函数
    mystring(char s[]) :pstr(s), length(strlen(s)) {}//有参构造函数

    //重载输入输出
    friend istream& operator>>(istream& in, mystring& s);
    friend ostream& operator<<(ostream& out, const mystring &s);

    //重载+=
    void operator+=(const mystring &s)
    {
        strcat(this->pstr, s.pstr);
        this->length += strlen(s.pstr);
    }

    //重载=
    void operator=(const mystring &s) 
    {
        this->pstr = s.pstr;
        this->length = strlen(s.pstr);
    }

    //重载==
    int operator==(const mystring &s)
    {
        return strcmp(this->pstr, s.pstr) == 0;
    }

    //重载!=
    int operator!=(const mystring &s)
    {
        return strcmp(this->pstr, s.pstr);
    }

    //重载>
    int operator>(const mystring &s) 
    {
        return strcmp(this->pstr, s.pstr) > 0;
    }

    //重载<
    int operator<(const mystring &s)
    {
        return strcmp(this->pstr, s.pstr) < 0;
    }

    //重载下标运算符
    char operator[](int n) 
    {
        return *(this->pstr + n);
    }

private:
    char* pstr;
    int length;
};

istream& operator>>(istream& in, mystring& s)
{
    static  char str[50];
    cout << "请输入str数组的元素:";
    in >> str;

    s.pstr = str;
    s.length = strlen(str);

    return in;
}

ostream& operator<<(ostream& out,const mystring &s) 
{
    out << s.pstr;
    return out;
}


int main()
{
    char str[20];
    mystring s1(str);
    mystring s2;

    cout << "请输入s2:" << endl;
    cin >> s2;
    cout << s2 << endl;

    s2 += s1;
    cout <<"s1+=s2后s2为:"<< s2 << endl;

    s2 = s1;
    cout << s2[3] << endl;
    if (s1 != s2) {
        cout << "s1!=s2" << endl;
    }
    if (s1 == s2) {
        cout << "s1==s2" << endl;
    }
    if (s1 > s2) {
        cout << "s1>s2" << endl;
    }
    if (s1 < s2) {
        cout << "s1<s2" << endl;
    }


    return 0;
}
  • 写回答

4条回答 默认 最新

  • 真相重于对错 2023-04-30 17:53
    关注

    代码有问题,
    const 是没有用错,const t& 有个重要做用是绑定临时变量 比如 cout<<(s1+s2)那么s1+s2必然有一个临时变量 然后那个临时变量通过cout输出,如果不用const mstring& 则无法通过引用绑定 。例如还有s=s1+s2+s3 这样的代码必然中间要产生临时变量
    static 不出问题,是因位你的代码有问题。
    你没有考虑深拷贝。s1=s2这样的代码s1,s2必然会同时引用一个char* ,当对象被回收时必然报错

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 5月8日
  • 已采纳回答 4月30日
  • 修改了问题 4月30日
  • 创建了问题 4月30日

悬赏问题

  • ¥66 关于川崎机器人调速问题
  • ¥15 winFrom界面无法打开
  • ¥15 crossover21 ARM64版本安装软件问题
  • ¥15 mymetaobjecthandler没有进入
  • ¥15 mmo能不能做客户端怪物
  • ¥15 osm下载到arcgis出错
  • ¥15 Dell g15 每次打开eiq portal后3分钟内自动退出
  • ¥200 使用python编写程序,采用socket方式获取网页实时刷新的数据,能定时print()出来就行。
  • ¥15 matlab如何根据图片中的公式绘制e和v的曲线图
  • ¥15 我想用Python(Django)+Vue搭建一个用户登录界面,但是在运行npm run serve时报错了如何解决?