?帮忙看看简单的重载运算符有何问题
gl615 2008-05-11 03:05:17 一道作业题。
但刚写完第四个函数就出错了,很郁闷...。
请好心人指点。
先谢谢了。。
===================================================================================================
#include <iostream>
using namespace std;
class MyString
{
public:
int Getlength(); // 1
MyString(); // 2
MyString(char* str); // 3
MyString(MyString& another); // 4
MyString operator+(const MyString& another); // 5
MyString& operator=(const MyString& another); // 6
bool operator==(const MyString& another)const; // 7
char& operator[](int pos); // 8
operator char*(); // 9
protected:
friend ostream& operator<<(ostream& o,MyString& p); // 10
char* m_data;
int length;
};
int MyString::Getlength()
{
return length;
}
MyString::MyString()
{
m_data=new char[1];
m_data[0]='\0';
length=0;
}
MyString::MyString(char* str)
{
length=strlen(str);
m_data=new char[length+1];
int i;
for(i=0;i<length;i++)
{
m_data[i]=str[i];
}
m_data[i]='\0';
}
MyString::MyString(MyString& another)
{
length=another.Getlength();
m_data=new char[length+1];
int i;
for(i=0;i<length;i++)
{
m_data[i]=another[i];
}
m_data[i]='\0';
}
MyString MyString::operator+(const MyString& another)
{
int t = length + another.Getlength(); ----------------------------------// 62 error 1
MyString result(t); ----------------------------------------------------// 63 error 2
int i,j;
for(i=0;i<length;i++)
{
result[i]=m_data[i];
}
for(i=length,j=0;i<t,j<another.Getlength();i++,j++) -------------------// 69 error 3
{
result[i]=another[j];-------------------------------------------// 71 error 4
}
result[t]='\0';
return result;
}
void main()
{
MyString a="hehe";
}
================================================================================================
Compiling...
aaa.cpp
C:\Program Files\Microsoft Visual Studio\MyProjects\aaa\aaa.cpp(62) : error C2662: 'Getlength' : cannot convert 'this' pointer from 'const class MyString' to 'class MyString &'
Conversion loses qualifiers
C:\Program Files\Microsoft Visual Studio\MyProjects\aaa\aaa.cpp(63) : error C2664: '__thiscall MyString::MyString(char *)' : cannot convert parameter 1 from 'int' to 'char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
C:\Program Files\Microsoft Visual Studio\MyProjects\aaa\aaa.cpp(69) : error C2662: 'Getlength' : cannot convert 'this' pointer from 'const class MyString' to 'class MyString &'
Conversion loses qualifiers
C:\Program Files\Microsoft Visual Studio\MyProjects\aaa\aaa.cpp(71) : error C2678: binary '[' : no operator defined which takes a left-hand operand of type 'const class MyString' (or there is no acceptable conversion)
Error executing cl.exe.
aaa.exe - 4 error(s), 0 warning(s)
-----------------------------------------------------------------------------------------------------
我用的是VC++6.0编译器。