对于我的CS课程,我们的老师希望我们创建自己的字符串类。我刚刚开始阶段,目前正在尝试重载operator+
。他希望它作为非会员职能。以下是我到目前为止的情况:
这是String
头文件:
#include <iostream>
#include <stdio.h>
#include <cstring>
#ifndef STRING_HPP
#define STRING_HPP
class String
{
private:
int len;
char* str;
public:
String(); // default constructor
String(String const& s); // copy constructor
String(char const* s); // C-string constructor
~String() {delete str;}; // destructor
char* const getString(); //get string for printing
String& operator=(char const* c);
String& operator=(String const& s);
};
inline std::ostream& operator<<(std::ostream& os, String s)
{
return os << s.getString();
}
String operator+(String const& lhs, String const& rhs) {
len = lhs.len + rhs.len;
str = new char[len];
std::strcat(str,lhs);
std::strcat(str,rhs);
}
#endif
这是String.cpp
文件:
#include "string.hpp"
#include <cstring>
#include <iostream>
String::String()
{
len = 0;
str = new char[len];
}
String::String(String const& s) // copy constructor
{
len = s.len;
str = new char[len];
std::strcpy(str,s.str);
}
String::String(char const* s) // C-string constructor
{
len = std::strlen(s);
str = new char[len];
std::strcpy(str,s);
}
char* const String::getString()
{
return str;
}
String& String::operator=(char const* c)
{
// 1: allocate new memory and copy the elements
int newLen = std::strlen(c);
char* newStr = new char[newLen];
std::strcpy(newStr,c);
// 2: deallocate old memory
delete [] str;
// 3: assign the new memory to the object
str = newStr;
len = newLen;
}
String& String::operator=(String const& s)
{
// 1: allocate new memory and copy the elements
int newLen = s.len;
char* newStr = new char[newLen];
std::strcpy(newStr,s.str);
// 2: deallocate old memory
delete [] str;
// 3: assign the new memory to the object
str = newStr;
len = newLen;
}
这是main
的实现:
#include "string.hpp"
#include <iostream>
int main()
{
String s1;
String s2 = "test";
String s3 = s2;
std::cout << s1 << '\n';
std::cout << s2 << '\n';
std::cout << s3 << '\n';
String a = "one";
String b = "two";
a = b;
b = "three";
std::cout << a << '\n';
std::cout << b << '\n';
String hello = "hello ";
String world = "world";
String concat = hello + world;
std::cout << concat << '\n';
}
一切都有效,直到最后concat
。我不能改变Main.cpp
,因为它是由教授提供的。
任何人都可以帮助我指出让operator+
工作的正确方向吗?
答案 0 :(得分:2)
您正在使用
str = new char[len];
所有功能。它没有足够的内存来保存终止空字符。你需要使用:
str = new char[len+1];
在operaor+
函数中,在内存分配后使用strcat
导致未定义的行为,因为str
未初始化。
您需要使用:
str = new char[len+1];
str[0] = '\0';
std::strcat(str,lhs);
std::strcat(str,rhs);
或
str = new char[len+1];
std::strpy(str,lhs); // strcpy, not strcat
std::strcat(str,rhs);
<强>更新强>
operator+()
的完整实施:
String operator+(String const& lhs, String const& rhs) {
int len = lhs.len + rhs.len;
char* str = new char[len+1];
std::strcpy(str,lhs);
std::strcat(str,rhs);
String ret(str);
delete [] str;
return ret;
}
如果实施String::operator+=(String const& rhs)
,可以简化功能。然后,您可以使用:
String operator+(String const& lhs, String const& rhs) {
String ret(lhs);
ret += rhs;
return ret;
}