标题:请教一下:字符串减法运算符重载,运行出错,程序似乎没有问题!
只看楼主
用户名
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2005-3-3
 问题点数:0 回复次数:0 
请教一下:字符串减法运算符重载,运行出错,程序似乎没有问题!
#include <iostream.h>
#include <string.h>
class MyString
{
public:
    MyString() {m_data = NULL;}            
    MyString(const char *str);                    
    ~MyString();                    
    MyString operator-(const MyString &other);
    MyString operator=(const MyString &other);
    friend ostream &operator<<(ostream &stream, const MyString &str);
                        //重载输出运算符"<<"
private:
    char *m_data;   
};
#define NULL 0
MyString::~MyString()
{
    if(m_data)
        delete [] m_data;
    m_data = NULL;
}
MyString::MyString(const char *str)
{
    if(str == NULL)
    {
        m_data = new char[1];
        *m_data = '\0';
    }
    else
    {
        int length = strlen(str);
        m_data = new char[length+1];
        strcpy(m_data, str);
   
    }
}
MyString MyString::operator=(const MyString &other)
{  
    if(this==&other)
       return *this;
    delete m_data;
    m_data=new char[strlen(other.m_data)+1];
    strcpy(m_data,other.m_data);
    return *this;
        
}

MyString  MyString::operator-(const MyString &other)
{   int i,j,t=0,m;
    MyString temp;
    int length1 = strlen(other.m_data);
    int length2 = strlen(m_data);
for(;t<length2;t++)
{
   
    i=t;j=0;
    while(*(m_data+i)!='\0'&&*(other.m_data+j)!='\0')
    if(m_data[i]==other.m_data[j])
    {i++;j++;}
   else{
    i=i-j+1;
    j=0;
   }
if(*(other.m_data+j)=='\0')
{m=i-j;
while(*(m_data+m)!='\0')
{
*(m_data+m)=*(m_data+m+length1);
m++;
}
}
}
temp.m_data=new char[strlen(m_data)+1];
strcpy(temp.m_data,m_data);
    return temp;
}

ostream& operator<<(ostream &stream, const MyString &str)
{
    stream<<str.m_data;
    return stream;
}
void main()
{
    MyString str1("abcdefgabef"), str2("ef");
    MyString str3;
    cout<<"str1->"<<str1<<endl;
    cout<<"str2->"<<str2<<endl;
    str3 =str1-str2;
   
cout <<"str3=str1-str2,str3->"<<str3<<endl;
}
搜索更多相关主题的帖子: 运算符 减法 字符 重载 
2007-12-10 10:24



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-191478-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.580132 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved