C ++函数通过strlen()运行'string'类型参数,将新值保存到虚拟类实例,将虚拟类传递给新函数。为什么?

时间:2014-10-20 00:23:34

标签: c++ linked-list

我试图编写一个程序,通过名称和评级(从高到低)使用C ++中的双线程链接列表对酿酒厂进行排序。有一个班级列表和班级酿酒厂。 Winery的每个实例都存储名称,位置,英亩和评级。

主要是一个功能' insertWinery'被称为带有四个参数:名称,位置,英亩,评级。这个函数创建了Winery的新实例,* w,它编辑了#34; name"和"位置"使用strlen。然后它将这两个参数的数值保存在名为" nm"的新变量中。和" loc"它复制到虚拟' * w,'然后将* w传递给函数' insert'在list.cpp中,实际上插入。

我不明白为什么要将字符串更改为数值。我可以遍历字符串中的字符并按字母顺序排列不同的酿酒厂,然后使用循环在列表中找到正确的位置以按名称插入新的酿酒厂,那么为什么我要将其设为数字​​呢?当然,用数字搜索更容易,但是我不知道这个数字与酒厂的正确字母顺序有什么关系,并且可能有酒庄的名字中有相同数量的字符。

我将附上一份功能< insertWinery'这里:

static void insertWinery(char *name, char *location, int acres, int rating)
{
    Winery *w;
    char   *nm  = new char[strlen(name) + 1];
    char   *loc = new char[strlen(location) + 1];

    strcpy(nm, name);
    strcpy(loc, location);
    w = new Winery(nm, loc, acres, rating);
    wineries-> insert(*w);
    delete[] nm;
    delete[] loc;
    delete[] w;
}

* w传递给的插入函数是list类型:

void List::insert(const Winery& winery)
{
// code to be written
}

如果需要更多信息,请告诉我,但我认为不仅仅是必要的。我只是想知道为什么在将* w传递给List :: insert(const Winery& winery)之前,名称和位置的值被更改为数字。我需要编写插入函数,但我不知道如何处理这些值,或者当我有随机字符串长度而不是现在的名字时,我应该如何在列表中运行名称线程。

非常感谢任何帮助,谢谢

编辑:酒庄建设者:

Winery::Winery(const char * const name, const char * const location, const int acres, const int rating) :
    name(NULL),
    location(NULL),
    acres(acres),
    rating(rating)
{
    if (this->name)
        delete[] this->name;
    this->name = new char[strlen(name) + 1];
    strcpy(this->name, name);

    if (this->location)
        delete[] this->location;
    this->location = new char[strlen(location) + 1];
    strcpy(this->location, location);
}

1 个答案:

答案 0 :(得分:1)

  

我不明白为什么要将字符串更改为数值。

这不是你的代码正在做的事情。以下代码:

char   *nm  = new char[strlen(name) + 1];

分配新内存,字符数的长度为name加1.它根本不会将名称转换为数字。然后strcpy(nm, name);将参数name中的字节复制到nm指向的新分配的内存中。

您的代码可能实际上并不需要执行此复制。但是,如果不知道Winery构造函数正在做什么,就无法确定。