我真的需要通过查看主程序和示例执行输出来理解如何编写类(声明和定义)

I really need help understanding how to write a class (declaration and definition) just by looking at a main program and sample execution output

本文关键字:何编写 定义 声明 输出 主程序 执行 我真的需要      更新时间:2023-10-16

我看过一个例子,我正试图通过查看主文件和输出来了解如何编写.h和.cpp文件

我有一门课叫Flex:

#include <iostream>
#include "flex.h"
using namespace std;
int main()
{
    Flex a, b("Merry"), c("Christmas");
    cout << a << ',' << b << ',' << c << endl;
    b.cat(a);
    cout << b << endl;
    b.cat(c);
    cout << b << endl;
    c.cat(c);
    c.cat(c);
    cout << c << endl;
    return 0;
}

执行输出为:

    * *,*Merry*,*Christmas*
    *Merry *
    *Merry Christmas*
    *ChristmasChristmasChristmasChristmas*

然后,声明/定义文件应该如下所示:

#include <iostream>
using namespace std;
class Flex
{
   friend ostream& operator<< (ostream& s, const Flex& f);
public:
   Flex();          // default constructor
   Flex(const char *);      // constructor with parameters
   ~Flex();         // destructor (not specifically required)
   void cat(const Flex & f);    // cat function -- concatenation
private:
   char * str;          // variable length string
   int size;
};

 #include <iostream>
 #include <cstring>
 #include "flex.h"
 using namespace std;
 ostream& operator<< (ostream& s, const Flex& f)
 {
    s << '*' << f.str << '*';
    return s;
 }
 Flex::Flex()
 {
    size = 1;           // size doesn't include null char
    str = new char[size+1]; // allocate +1 for null char
    strcpy(str," ");
 }
 Flex::Flex(const char * s)
 {
    size = strlen(s);
    str = new char[size+1];
    strcpy(str,s);
 }
 Flex::~Flex()
 // not specifically required by the specs, but a good idea to have this
 {
    delete [] str;
 }
 void Flex::cat(const Flex & f)
 // this function can also be made easier through the use of the
 // strcat library function for concatenating strings.
 // dyanamic reallocation still required, though.
 {
    int newsize = size + strlen(f.str);
    char * temp = new char[newsize+1];  // allocate with room for ''
    strcpy(temp,str);           // copy this string to temp
    for (int i = 0; i <= f.size; i++)
        temp[size+i] = f.str[i];    // concatenate f.str to temp,
                        //   including ''
    delete [] str;          // delete old array
    str = temp;             // set str to new one
    size = newsize;         // update size tracker
 }

这个问题可能很难解释,但一个人如何看待主程序并立即知道他要写什么课?

我需要为一个涉及统计数据的类做这件事。我还没有一个主程序,但如果我不再使用字符,我们会有什么不同?如何通过查看主文件和输出来表示统计类?

运算符<lt;发送'*' << f.str << '*'(其中f.str是您的,Flex对象,str值)您有Flex 类的构造函数

Flex::Flex()
{
   size = 1;            // size doesn't include null char
   str = new char[size+1];  // allocate +1 for null char
   strcpy(str," ");
}
Flex::Flex(const char * s)
{
   size = strlen(s);
   str = new char[size+1];
   strcpy(str,s);
}

当您初始化像Flex这样的对象时("测试")。您的a.str=="测试"。当Flex为a()时,则a.str=="。函数cat是concatanation 2值。如果b.cat(a),则意味着b.str=b.str+a.str

相关文章: