您的位置:首页 > 编程语言 > C语言/C++

第四章:运算符的重载的一系列问题(课堂作业)

2015-04-26 18:40 375 查看
#include<istream>
using namespace std;
#include<string.h>

class String
{

public:

String();

virtual ~String();

String(int n);

String(const String &s2);

String(const char *str);

String & operator = (const String &s1);

friend bool operator >(String &string1, String &string2);

friend bool operator <(String &string1, String &string2);

friend bool operator == (String &string1, String &string2);

friend bool operator <= (String &string1, String &string2);

friend bool operator >= (String &string1, String &string2);

friend ostream& operator << (ostream& , String &);

private:

char *s;

};

String::String()//初始化,默认长度为100
{
s = new char[100];

s[0] = '\0';
}

String::String(int n)//构造一个大小为n的数组
{
s = new char
;

s[0] = '\0';
}

String::~String()//析构
{
if(s)
{
delete s;
}
s = NULL;
}

String::String(const String &s2)//拷贝构造函数
{
this->s = new char [strlen[s2.s]+1]  ;  //ERROR :C:\Users\Administrator\Desktop\I  can  do  it\fsada.cpp(69) : error C2107: illegal index, indirection not allowed
//ERROR: C:\Users\Administrator\Desktop\I  can  do  it\fsad//error //C2440: 'initializing' : //cannot convert from 'char *' to 'int'

s[0] = '\0';

strcpy(s, s2.s);
}

String::String(const char *str)
{
s = new char[strlen[str]+1];//同上 = =。

s[0] = '\0';
}

String& String :: operator = (const String &s1)//赋值构造函数
{
if(this == &s1)
{
return *this;
}
else
{
delete   []s1; //ERROR :No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
//ERRORE:fatal error C1903: unable to recover from previous error(s); stopping compilation

s1 = new char [strlen[s1.s]+1];

return *this;
}

}

bool operator > (String &string1, String &string2)
{
if(strcmp(string1.s , string2.s) > 0)

return true;

else

return false;
}

bool operator < (String &string1, String &string2)
{
if(strcmp(string1.s , string2.s) < 0)

return true;

else

return false;
}

bool operator == (String &string1, String &string2)
{
if(strcmp(string1.s , string2.s) == 0)

return true;

else

return false;
}

bool operator <= (String &string1, String &string2)
{
if(strcmp(string1.s , string2.s) > 0)

return false;

else

return true;
}

bool operator >= (String &string1, String &string2)
{
if(strcmp(string1.s , string2.s) < 0)

return false;

else

return true;
}

ostream& operator << (ostream& output , String & s3)
{

output << s3.s << endl;

return output;

}
没办法找出错误的原因。无法运行  = =。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息