【发布时间】:2015-10-21 05:07:23
【问题描述】:
我正在尝试实现字符串类。这是我所做的:
#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] = '\0';
}
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] = '\0';
}
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] = '\0';
}
int main() {
MyString word1 ("stackoverflow");
MyString word2;
word2 = word1;
word1.print();
word2.print();
}
我编译了它,这是我得到的:
堆栈溢出
堆栈溢出
进程返回 0 (0x0) 执行时间:0.050 s 按任意键继续。
虽然根据上面的结果看起来是正确的,但我想知道它真的正确吗?我对 C 风格的字符串不太熟悉,所以我很担心 例如关于行:
content [length] = '\0';
由于 C 风格的字符串末尾有空终止符,我想终止我的数组,但这是正确的方法吗? 我使用了动态内存分配,我也想知道我是否正确释放了资源? 是否有一些内存泄漏? 提前致谢。
编辑1: 我还重载了operator +(我想加入“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 ] = '\0';
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 s 按任意键继续。
我希望这段代码没有问题:)
编辑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] = '\0';
return temp;
}
现在可能更好,因为没有 if :)
【问题讨论】:
-
我希望这是一个作业。 C++ 世界最不需要的就是另一个字符串类。
-
别担心,这是作业:)
-
您对
content [length] = '\0'的分配超出了您的分配一个字符。如果要添加 NULL,则需要分配长度 + 1 个字符。 -
在我看来,BSTR 是一个很好的实现。如果我是你,我会寻找源头并仔细研究它。它在
comutil.h中声明,但我在这个系统上没有 C++,所以我不能更具体。 -
@etf:从 0 跑到 length。由于
strlen返回了一个有效值(或者您可以假设它确实如此),那么您知道末尾有一个 0。只需将其复制为字符串的终止符即可。
标签: c++ arrays string implementation dynamic-memory-allocation