鱼C论坛

 找回密码
 立即注册
查看: 2078|回复: 3

问下这个代码为什么报错了

[复制链接]
发表于 2019-4-19 15:01:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <iostream>
#include <string.h>
using namespace std;

class MyString
{
  private:
    char *str;//保存字符串的堆空间地址的指针

  public:
    MyString()//无参构造函数
    {
        this->str = new char[1000];
    }
    MyString(char *str)//有参普通构造函数
    {
        this->str = str;
    }
    MyString(MyString &S1)//深层拷贝构造函数
    {
        this->str = S1.str;
    }
    ~MyString()//析构函数
    {
        if (this->str != NULL)
            delete[](this->str);
        this->str = NULL;
    }
    char getCharAt(int index)//得到字符串中第index个字符
    {
        return str[index];
    }
    int getLen()//得到字符串的长度
    {
        return (sizeof(str) - 1);
    }
    void display()//显示字符串内容
    {
        cout << this->str;
    }

    void putChar(char *str)//保存字符串的堆空间地址的指针
    {
        this->str = str;
    }

    MyString operator+(MyString &S1)//实现2个字符串连接
    {
        MyString aux;
        aux = strcat(this->str, S1.str);
        return aux;
    }

    bool operator<(MyString &S1)//比较2个字符串
    {
        //如果返回值 < 0,则表示 str1 小于 str2。
        // 如果返回值 > 0,则表示 str2 小于 str1。
        // 如果返回值 = 0,则表示 str1 等于 str2。
        int aux = strcmp(this->str, S1.str); // a < b ?
        if (aux < 0)
        {
            return true;
        }
        return false;
    }

    ostream operator<<(MyString &S1)//析取运算符重载;用于输出字符串内容
    {
        S1.display();
    }
};

int main()
{
    char * str;
char * aux = "12345";
    MyString S1(str); //有参构造
    S1.putChar(aux);
    S1.display();
    cout << " true : " << S1.getCharAt(2) << endl;
    MyString S2(S1); ////深度拷贝
    S2.display();
    cout << " false:" << S2.getLen() << endl;
    MyString S3; ////无参构造
    S3.putChar(aux);
    S3.display();
    cout << S3.getLen() << endl;
    bool result;
    result = S1 < S3;
    system("pause");
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-4-19 15:03:49 | 显示全部楼层
c++大佬们
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-4-19 15:04:29 | 显示全部楼层
在线等急
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-4-20 14:38:23 | 显示全部楼层
本帖最后由 Croper 于 2019-4-20 14:40 编辑

我可以帮你,而且代码都写好了,但是我觉得贴出来肯定就被你复制粘贴拿去应付作业了,
我觉得你应该去了一下什么叫深层拷贝,什么叫重载<<运算符
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-3 14:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表