读书人

如何把上面这个C++程序改写成为类的形

发布时间: 2012-09-01 09:33:02 作者: rapoo

怎么把下面这个C++程序改写成为类的形式
新手都喜欢把程序写在一个主函数里。因为既然是C++,所以用类的形式更能体现C++特点。如果要把下面这个程序改写成类的形式,应该怎么改写呢?我试着改写了一上午了也不知道怎么以类的形式表达。各位大神谁来帮帮忙哦?只要在一个文件名为in的里面写入ABCD,而另外一个文件名为out的没有任何内容的文件在程序运行后能显示DCBA就行。

C/C++ code
#include <iostream>#include <fstream>using namespace std;int main(){    ifstream ifs("in.txt");    if (!ifs)    {        cout << "File open failed!" << endl;        return 1;    }    const int ARRAY_SIZE = 64;    char *array = new char[ARRAY_SIZE];    int index = 0;    while (ifs >> array[index])    // 文件最多 ARRAY_SIZE - 1 个非空白字符    {        index ++;    }    int realSize = index;    array[realSize] = 0;    // 使用插入排序作为例子,其它排序方法楼主自己实现    for (int i=1; i<realSize; i++)    {        int temp = array[i];        int j = i;        for (; j>0 && array[j-1] < temp; j--)        {            array[j] = array[j-1];        }                array[j] = temp;    }    // output to console for test    for (int i=0; i<realSize; i++)    {        cout << array[i] << " ";    }        cout << endl;    ofstream ofs("out.txt");    if (!ofs)    {        cout << "File create failed!" << endl;        delete [] array;        return 1;    }    for (index=0; index < realSize; index++)    {        ofs << array[index] << " ";    }    delete [] array;    ifs.close();    ofs.close();    cin.get();    return 0;}// 输出示例:/* 输入文件:in.dat   A B C D   输出:D B C A   输出文件:out.dat   D B C A*/


[解决办法]
探讨

引用:
把这两个功能封装在一个类中的两个函数就ok

都说了,我已经搞了一上午了,还是想不出来怎么办。你说的这个方法,只要学过类的话,都知道的,可是我在具体实现中出问题了。

读书人网 >C++

热点推荐