I need help with this homemade String. I can't get it work. I am told not to do anything with the main.cpp, only String.cpp and String.h am I allowed to do what ever I want. This is what I have done so far.
////////////////////////////////////////////////////////////////
// String.h
#ifndef _STRING_H_
#define _STRING_H_
#include <iostream>
using std:stream;
class String
{
private:
char * str;
int len;
public:
String();
String(String const &s);
String(char const* s);
~String();
String &operator=(String const &s);
friend ostream &operator<<(ostream &o, String const &s);
String operator+(String const &s) const;
};
#endif
/////////////////////////////////////////////////////////
// String.cpp
#include <iostream>
#include "String.h"
String::String()
{
str = new char[1];
str[0] = '\0';
len = 1;
}
String::String(String const &s)
{
str = new char[0];
*this = s;
}
String::String(const char* s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
String & String:perator=(String const &s)
{
if (this != &s)
{
delete [] str;
str = new char[s.len + 1];
for (int i = 0; i <= s.len; i += 1)
str[i] = s.str[i];
len = s.len;
}
return *this;
}
String String:perator +(String const &s) const
{
char *temp = new char[len + s.len + 1];
for (int i = 0; i < len; i += 1)
temp[i] = str[i];
for (i = 0; i <= s.len; i += 1)
temp[i + len] = s.str[i];
String res(temp);
return res;
}
String::~String()
{
delete [] str;
}
ostream &operator<<(ostream &o, String const &s)
{
o << s.str;
return o;
}
///////////////////////////////////////////////////////////////
// main.cpp
#include "String.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
String t1("Donald");
String t2;
String t3(t1);
t2 = "Here comes " + t1; // I get an error message
t3 = t2 + " Duck";
cout << t1 << endl;
cout << t2 << endl;
cout << t3 << endl;
return 0;
}
// Error message in MS Visual C++ 6.0 sp5, Windows 2000
// binary '+': no global operator defined which takes
// type 'class String' for there is no acceptable conversion
Thanks.
Mikael Raja
[email protected]