I just developed a String class and overloaded =, <<, [] operators but my operator+ is not working, a little help with it please!
Class:
class String
{
private:
int length;
char *chars;
public:
String oprator+(String &obj);
}
Main Code:
int main ( )
{
String str1;
str1 = "This is first text";
String str2;
str2 = "This is second text";
String bigString = str1 + str2;
bigString = bigString + "This is third text";
}
operator+ overload:
String::String operator+ (String &obj)
{
String *temp = new String();
strcpy(temp->chars, chars);
strcat(temp->chars, obj.chars);
return *temp;
}
Your operator+
should read
class String
{
private:
int length;
char *chars;
String(const char* s, size_t n):
length( n ),
chars( new char[n] )
{
std::copy(s, s+length, chars);
}
public:
explicit String(size_t l):
length(l),
chars( new char[l] )
{
}
String(char const* s):
String(s, strlen(s) )
{
}
String(String const& s):
String(s.chars, s.length)
{
}
String& operator=(String s)
{
std::swap(chars, s.chars);
std::swap(length, s.length);
return *this;
}
~String() {delete[] chars;}
template<size_t N> String(const char s[N]):
String(s, N)
{
}
void append(String const& s)
{
char* tmp = new char[length + s.length];
std::copy(chars, chars+length, tmp);
std::copy(s.chars, s.chars + s.length, tmp + length);
delete[] chars;
chars = tmp;
}
template<typename S> friend S& operator<<(S&, String const&);
};
String operator+(String const& s1, String const& s2)
{
String merged(s1);
merged.append(s2);
return merged;
}
template<typename S> S& operator<<(S& stream, String const& s)
{
return stream << s.chars;
}
int main()
{
String s("bla");
std::cout << s << std::endl;
String s2 = s + "bla";
std::cout << s2 << std::endl;
}
You don't want to modify the argument, so it should be a const reference. Making it non-const prevents code like
bigString = bigString + "This is third text";
because the create temporary String, if you add a non-explicit constructor, cannot bind to an l-value reference.
And the operator should not be a member function, but a free function to take advantage of conversions on the first argument. With a free function, you can do
bigString = "This is third text" + bigString;
which is not possible with the member function because char const[]
does not have an operator+
which takes a String
.
PS: You may want to read Monoliths "Unstrung" for some critic of std::string's interface.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.