当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

C++中动态内存分配引发问题的解决方案

    假设我们要开发一个String类,它可以方便地处理字符串数据。我们可以在类中声明一个数组,考虑到有时候字符串极长,我们可以把数组大小设为200,但一般的情况下又不需要这么多的空间,这样是浪费了内存。对了,我们可以使用new操作符,这样是十分灵活的,但在类中就会出现许多意想不到的问题,本文就是针对这一现象而写的。现在,我们先来开发一个Wrong类,从名称上看出,它是一个不完善的类。的确,我们要刻意地使它出现各种各样的问题,这样才好对症下药。好了,我们开始吧!

 Wrong.h:

#ifndef WRONG_H_
#define WRONG_H_
class Wrong
{
private:
char * str; //存储数据
int len; //字符串长度

public:
Wrong(const char * s); //构造函数
Wrong(); // 默认构造函数
~Wrong(); // 析构函数
friend ostream & operator<<(ostream & os,const Wrong& st);
};
#endif

Wrong.cpp:

#include <iostream>
#include <cstring>
#include "wrong.h"
using namespace std;
Wrong::Wrong(const char * s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);

}//拷贝数据

Wrong::Wrong()
{
len =0;
str = new char[len+1];
str[0]='\0';

}

Wrong::~Wrong()
{
cout<<"这个字符串将被删除:"<<str<<'\n';//为了方便观察结果,特留此行代码。
delete [] str;
}

ostream & operator<<(ostream & os, const Wrong & st)
{
os << st.str;
return os;
}

test_right.cpp:

#include <iostream>
#include <stdlib.h>
#include "Wrong.h"
using namespace std;
int main()
{
Wrong temp("天极网");
cout<<temp<<'\n';
system("PAUSE");
return 0;
}

    运行结果:

  天极网

  请按任意键继续. . .

  大家可以看到,以上程序十分正确,而且也是十分有用的。可是,我们不能被表面现象所迷惑!下面,请大家用test_wrong.cpp文件替换test_right.cpp文件进行编译,看看结果。有的编译器可能就是根本不能进行编译!

共4页 首页 上一页 1 2 3 4 下一页 尾页 跳转到
相关内容
赞助商链接