C++面试中遇到的题目,下面是我编译通过的代码,有不足之处,可以交流指出。
mstring.h
#ifndef MSTRING_H
#define MSTRING_H
#include <iostream>
class MString
{
friend std::ostream& operator<<(std::ostream& os, MString& str);
friend std::istream& operator>>(std::istream& os, MString& str);
public:
MString(const char*str = NULL);
MString(const MString&str);
~MString(void);
MString& operator=(const MString& other);
MString& operator+(const MString&other);
bool operator==(const MString& other);
int len(void);
private:
char* m_data;
};
#endif // MSTRING_H
mstring.cpp:
#include "mstring.h"
#include<stdio.h>
#include<string.h>
MString::MString(const char *str)
{
if(str == NULL)
{
this->m_data=NULL;
}
else
{
this->m_data = new char[strlen(str)+1];
strcpy(this->m_data,str);
}
}
MString::MString(const MString &str)
{
if(str.m_data == NULL)
{
this->m_data=NULL;
}
else
{
this->m_data = new char[strlen(str.m_data)+1];
strcpy(this->m_data,str.m_data);
}
}
MString::~MString()
{
if(this->m_data)
{
delete[] this->m_data;
this->m_data=NULL;
}
}
MString &MString::operator=(const MString &other)
{
if(this!=&other)
{
if(this->m_data!=NULL)
{
delete[] this->m_data;
this->m_data=NULL;
}
if(other.m_data==NULL)
{
this->m_data=NULL;
}
else
{
this->m_data = new char[strlen(other.m_data)+1];
strcpy(this->m_data,other.m_data);
}
}
return *this;
}
MString& MString::operator+(const MString &other)
{
MString *newString =new MString();
if(other.m_data==NULL)
{
return *this;
}
else if(this->m_data ==NULL)
{
*newString = other;
}
else
{
newString->m_data= new char[strlen(other.m_data)+strlen(this->m_data)+1];
strcpy(newString->m_data,this->m_data);
strcat(newString->m_data,other.m_data);
}
return *newString;
}
bool MString::operator==(const MString &other)
{
if(this->m_data!=other.m_data)
{
if(this->m_data==NULL||other.m_data==NULL)
{
return false;
}
else if(strlen(this->m_data)!=strlen(other.m_data))
{
return false;
}
else
{
return strcmp(this->m_data,other.m_data)?false:true;
}
}
return true;
}
int MString::len()
{
return strlen(m_data);
}
std::ostream& operator<<(std::ostream& os, MString& str)
{
os<<str.m_data;
return os;
}
std::istream& operator>>(std::istream& os, MString& str)
{
os>>str.m_data;
return os;
}