C++-字符串类的实现
C++ - implementation of string class
我正在尝试实现字符串类。以下是我所做的:
#include <iostream>
#include <cstring>
using namespace std;
class MyString{
private:
char * content;
int length;
public:
MyString ();
MyString ( const char * );
~MyString ();
MyString ( const MyString & );
void print ( void );
void operator = ( const MyString );
};
MyString :: MyString () {
content = 0;
length = 0;
}
MyString :: MyString(const char *n) {
length = strlen (n);
content = new char [ length ];
for ( int i = 0 ; i < length ; i++ ){
content [i] = n [i];
}
content [length] = ' ';
}
MyString :: ~ MyString () {
delete [] content;
content = 0;
}
MyString :: MyString ( const MyString & x ) {
length = x.length;
content = new char [length];
for( int i = 0 ; i < length ; i++ ){
content [i] = x.content [i];
}
content [length] = ' ';
}
void MyString :: print( void ) {
cout <<""<< content << endl;
}
void MyString :: operator = ( const MyString x ) {
length = x.length;
content = new char [length];
for( int i = 0 ; i < length ; i++ ){
content [i] = x.content [i];
}
content [length] = ' ';
}
int main() {
MyString word1 ("stackoverflow");
MyString word2;
word2 = word1;
word1.print();
word2.print();
}
我编译了它,这就是我得到的:
堆叠式
堆叠式
进程返回0(0x0(执行时间:0.050秒按任意键继续。
虽然从上面的结果来看它看起来是正确的,但我想知道它真的正确吗?我对C型字符串不太熟悉,所以我很担心例如关于线路:
content [length] = ' ';
由于C样式字符串的末尾有null终止符,我想终止我的数组,但这是正确的方法吗?我使用了动态内存分配,我还想知道我是否正确地释放了资源?是否有内存泄漏?提前谢谢。
第1版:我还重载了opeartor+(我想加入"MyStrings"(,下面是代码:
MyString MyString :: operator + ( const MyString & x ){
MyString temp;
temp.length = x.length + length;
temp.content = new char [ temp.length + 1 ];
int i = 0, j = 0;
while ( i < temp.length ) {
if (i < length ) {
temp.content [i] = content [i];
}
else {
temp.content [i] = x.content [j];
j ++;
}
i ++;
}
temp.content [ temp.length ] = ' ';
return temp;
}
这是主程序:
int main()
{
MyString word1 ( "stack" );
MyString word2 ( "overflow" );
MyString word3 = word1 + word2;
word3.print();
word3 = word2 + word1;
word3.print();
}
结果是:
堆叠式
飞越堆栈
进程返回0(0x0(执行时间:0.040秒按任意键继续。
我希望这个代码没有问题:(
第2版:以下是使用for循环而不是while的+运算符的实现:
MyString MyString :: operator + (const MyString & x){
MyString temp;
temp.length = x.length + length;
temp.content = new char [temp.length+1];
for( int i = 0 ; i < length ; i++ ){
temp.content[i] = content[i];
}
for( int i = length , j = 0 ; i <temp.length ; i++, j++){
temp.content[i] = x.content[j];
}
content[temp.length] = ' ';
return temp;
}
现在可能更好了,因为没有if:(
您正试图为content[length]
分配一个值,但尚未为访问content[length]
分配足够的内存。如果是length == 10
,则可以访问content[0]
到content[9]
,但不能访问content[10]
。
当然,这可以通过从两个构造函数中删除行content[length] =
来解决,或者如果要追加