不锈钢四方料重量计算:C++试题 关于运算符重载 大虾请进

来源:百度文库 编辑:中科新闻网 时间:2024/05/09 19:30:54
对于下面的类MyString,要求重载一些运算符后可以计算表达式:a=b+c;,其中a,b,c都是类MyString的对象.请重载相应的运算符并编写程序测试

class MyString{
public:
MyString(char *s){
str=new char[strlen(s)+1];
strcpy(str,s);
}
~MyString(){
delete[]str;
}
private:
char *str;
};

急,两天内评出最佳,谢谢帮忙!

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

class MyString
{
public:
MyString(char *s)
{
str=new char[strlen(s)+1];
strcpy(str,s);
}

MyString()
{
str = new char;
str[0]='\0';
}

~MyString()
{
delete []str;
}

void PrintSelf()
{
cout<<str<<endl;
}

MyString& operator +(MyString &b) //字符串连接
{

char* temp = str;
str = new char[strlen(temp)+strlen(b.str)+1];
str =strcpy(str,temp);
delete []temp;
str = strcat(str,b.str);
return *this;
}

MyString& operator =(MyString &c) // 赋值函数
{
if(this == &c)return *this; //检查自赋值
delete []str; // 释放原有的内存资源
str = new char[strlen(c.str )+1]; // 分配新的内存资源
strcpy(str,c.str); // 并复制内容
return *this; // 返回本对象的引用
}
private:
char *str;
};

int main()
{
MyString a;
MyString b("BBB"),c("CCC");
a=b+c;
a.PrintSelf();
return 0;
}

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

class MyString
{
public:
MyString(char *s)
{
str=new char[strlen(s)+1];
strcpy(str,s);
}

MyString()
{
str = new char;
str[0]='\0';
}

~MyString()
{
delete []str;
}

void PrintSelf()
{
cout<<str<<endl;
}

MyString& operator +(MyString &b) //字符串连接
{

char* temp = str;
str = new char[strlen(temp)+strlen(b.str)+1];
str =strcpy(str,temp);
delete []temp;
str = strcat(str,b.str);
return *this;
}

MyString& operator =(MyString &c) // 赋值函数
{
if(this == &c)return *this; //检查自赋值
delete []str; // 释放原有的内存资源
str = new char[strlen(c.str )+1]; // 分配新的内存资源
strcpy(str,c.str); // 并复制内容
return *this; // 返回本对象的引用
}
private:
char *str;
};

int main()
{
MyString a;
MyString b("BBB"),c("CCC");
a=b+c;
a.PrintSelf();
return 0;
}

楼上很强