void read(cnode* head) { std::ifstream in; char a[20]; string b; double c; double d; in.open("D:\\《文件》\\数据结构程序设计\\消费者积分管理系统\\first.txt",ios::app); while (in >> a >> b >> c >> d) { cnode* p = new cnode(a, b, c, d, NULL); p->next = head->next; head->next = p; } if (head == NULL) cout << "加载失败,请检查后重试"; else cout << "加载成功"; } new cnode(a, b, c, d, NULL)这个语句出现“C++ 没有与参数列表匹配的构造函数 参数类型为: (char [20], std::string, double, double, int)”和“没有重载函数接受5个参数”的问题
时间: 2024-01-06 16:05:54 浏览: 28
根据编译器的错误提示,你定义的 `cnode` 类的构造函数并没有接受 `(char [20], std::string, double, double, int)` 这样的参数列表。你需要在 `cnode` 类中定义一个构造函数,接受这样的参数列表,并在构造函数中对类的成员变量进行初始化。
例如,你可以在 `cnode` 类的定义中加入以下构造函数:
```c++
cnode(char name[], std::string id, double score, double spend, cnode* n) {
// 对类的成员变量进行初始化
strcpy(this->name, name);
this->id = id;
this->score = score;
this->spend = spend;
this->next = n;
}
```
然后在 `read` 函数中使用这个构造函数:
```c++
cnode* p = new cnode(a, b, c, d, NULL);
```
相关问题
void read(cnode* head) { std::ifstream in; char a[20]; string b; double c; double d; in.open("D:\\《文件》\\数据结构程序设计\\消费者积分管理系统\\first.txt", ios::app); while (in >> a >> b >> c >> d) { cnode *p= new cnode(a,b,c,d,NULL); p->next = head->next; head->next = p; } if (head == NULL) cout << "加载失败,请检查后重试"; else cout << "加载成功"; }怎么改进
这段代码可以改进的地方有:
1. 打开文件时使用了硬编码路径,建议改为使用相对路径或用户自定义路径。
2. 打开文件时使用了 `ios::app` 模式,这样会将新数据追加到文件末尾。如果文件中已经存在数据,读取后会出现重复记录。建议改为 `ios::in` 模式,只读取文件中已有的数据。
3. 在读取数据时,没有进行错误处理和异常处理,容易导致程序崩溃。建议加入相关的判断和处理语句。
4. 在创建新节点时,没有进行内存分配错误的检查,容易导致程序崩溃。建议加入相关的判断和处理语句。
改进后的代码如下:
```
void read(cnode* head, const string& filename) {
std::ifstream in(filename);
if (!in) {
std::cout << "打开文件失败,请检查文件路径" << std::endl;
return;
}
char a[20];
string b;
double c;
double d;
while (in >> a >> b >> c >> d) {
cnode* p = new (std::nothrow) cnode(a, b, c, d, NULL);
if (!p) {
std::cout << "内存分配失败" << std::endl;
return;
}
p->next = head->next;
head->next = p;
}
if (head->next == NULL) {
std::cout << "文件中没有数据" << std::endl;
} else {
std::cout << "加载成功" << std::endl;
}
}
```
调用示例:
```
cnode* head = new cnode();
read(head, "first.txt");
```
void read(cnode* head) { std::ifstream in; char a[20]; string b; double c; double d; in.open("D:\《文件》\数据结构程序设计\消费者积分管理系统\first.txt",ios::app); while (in >> a >> b >> c >> d) { cnode* p = new cnode(a, b, c, d, NULL); p->next = head->next; head->next = p; } if (head == NULL) cout << "加载失败,请检查后重试"; else cout << "加载成功"; } new cnode(a, b, c, d, NULL)这个语句出现“C++ 没有与参数列表匹配的构造函数 参数类型为: (char [20], std::string, double, double, int)”和“没有重载函数接受5个参数”的问题请使用c++链表的存储结构和结构体指针修改
假设你的链表结构体定义如下:
```c++
struct cnode {
char a[20];
string b;
double c;
double d;
cnode* next;
};
```
则 `new cnode(a, b, c, d, NULL)` 这个语句需要修改如下:
```c++
new cnode{a, b, c, d, NULL}
```
这是因为 `new` 操作符在创建对象时需要使用大括号 `{}` 代替小括号 `()`,并且结构体类型的对象需要使用花括号 `{}` 包含成员初始化列表。