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?
我正试图编写一个程序,使用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
构造函数在做什么,就无法确定。
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数