你好开发者!我正在学习Skiena的算法设计手册中的算法.我有以下代码:
#include <stdio.h>
#include <stdlib.h>
typedef int item_type;
typedef struct{
item_type item;
struct list* next;
}list;
void insert_list(list **l, item_type x){
list *p;
p = malloc(sizeof(list));
p->item = x;
p->next = *l;
*l = p;
}
int main(){
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它在编译时给我警告:
gcc -Wall -o"test""test.c"(在目录中:/ home/akacoder/Desktop/Algorithm_Design_Manual/chapter2)test.c:在函数'insert_list'中:test.c:15:警告:从不兼容的指针赋值类型编译成功完成.
但是,当我将此代码重写为C++时:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef int item_type;
typedef struct{
item_type item;
struct list* next;
}list;
void insert_list(list **l, item_type x){
list *p;
p = malloc(sizeof(list));
p->item = x;
p->next = *l;
*l = p;
}
int main(){
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出了以下内容:
g ++ -Wall -o"chapter2""chapter2.cpp"(在目录:/ home/akacoder/Desktop/Algorithm_Design_Manual/chapter2)chapter2.cpp:15:错误:冲突声明'typedef struct list list' chapter2.cpp:14:错误:'struct list'有一个前面的声明'struct list' chapter2.cpp:在函数'void insert_list(list**,item_type)'中:chapter2.cpp:在函数'void insert_list(list**,item_type)'中:chapter2.cpp:19:错误:无效从'void*'转换为'list*'
任何人都可以解释为什么会这样吗?我怎样才能用C++重写它?
这是因为在类型转换方面,c ++比c更严格.
您的代码中还有许多其他错误.请注意,只需输入交流源代码,将文件重命名为.cpp&compiling using g++,就不会将交流源代码作为c ++.
如果你正在编写一个程序,c++请使用new¬ malloc,这样做你不需要显式地输入cast,如果是的话malloc.
两种情况下的问题都在结构定义中:struct list *next不引用您在声明过程中的结构.试试这个:
typedef struct list {
item_type item;
struct list* next;
} list;
Run Code Online (Sandbox Code Playgroud)
另外,在C++中你必须将void *返回者malloc转换为适当的指针类型(list *),C++对这些事情更加严格.另外,BTW,在C++中你可以完全不用你想要的typedef.
不同错误消息的原因是语言的差异.
在C中,编译器知道这struct list *是一个指向结构的指针,所以它不需要抱怨它实际上并不知道什么是"结构列表".但是,稍后,当您尝试从类型为"list*"(其类型为"指向匿名结构的指针")的指针分配此"struct list*"时,它会抱怨不匹配.
在C++中,"struct"声明或多或少等同于"class"声明(主要区别在于成员的默认可见性).除此之外,这意味着C++中的结构或多或少都是自动类型化的.因此,当编译器看到"struct list*next"时,它将它作为名为"list"的类的前向声明; 然后当它完成语句并处理typedef时,抛出一个错误,因为你试图将一些东西输入到已经(向前)声明为其他东西的标识符.然后它会发出更多错误,因为它实际上并不知道"列表"可能是什么,因为之前的错误.
C语言不允许任意指针转换,而C则允许.但由于这不被认为是好的样式,编译器会发出警告.
只需添加一个演员,它将解决这两个消息:
p = (list*)malloc(sizeof(list));
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想成为C++:
p = new list;
Run Code Online (Sandbox Code Playgroud)
但是,你应该声明构造函数等.