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

C++ function runs 'string' type arguments through strlen(), saves new values to dummy class instance, passes dummy class to new function. Why?

本文关键字:虚拟 函数 实例 为什么 新函数 类型参数 string strlen C++ 运行 保存      更新时间:2023-10-16

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

通常,会调用一个函数"insertWinery",该函数接受四个参数:名称、位置、英亩数、评级。此函数生成Winery的新实例*w,并使用strlen编辑"name"answers"location"。然后,它将这两个参数的数值保存在名为"nm"answers"loc"的新变量中,并将其复制到伪"*w"中,然后将*w传递到list.cpp中的函数"insert"中,该函数实际上执行插入操作。

我不明白为什么字符串被改成数值。我可以迭代字符串中的字符,按字母顺序排列不同的酒庄,然后使用循环在列表中找到正确的位置,按名称插入新酒庄,那么我为什么要把它变成一个数字呢?当然,用数字搜索更容易,但我不明白这个数字与酒庄的正确字母顺序有什么关系,而且可能有些酒庄的名字中有相同数量的字符。

我会在这里附上一份"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&wintery)之前,名称和位置的值被更改为数字。我需要编写insert函数,但我不知道该如何处理这些值,也不知道当我现在有随机字符串长度而不是名称时,应该如何在列表中运行名称线程。

任何帮助都将不胜感激,谢谢

编辑:酿酒师:

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);
}

我不明白为什么字符串被改成数值。

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

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

分配新内存,字符数name加1的长度。它根本没有将名称转换为数字。然后CCD_ 2将来自参数name的字节复制到由nm指向的新分配的存储器中。

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