C 指向并集中函数的指针
VisualStudio在此代码中给出错误C 指向并集中函数的指针,c,visual-studio,C,Visual Studio,VisualStudio在此代码中给出错误 typedef union { double value; double (*UnFunc)(double); double (*BiFunc)(double, double); double (*VarAssi)(vars_t *, elem_t, elem_t, error_t *); void (*FuncAssi)(custom_funcs_t *, elem_t, expr_t, error_t *); char de
typedef union
{
double value;
double (*UnFunc)(double);
double (*BiFunc)(double, double);
double (*VarAssi)(vars_t *, elem_t, elem_t, error_t *);
void (*FuncAssi)(custom_funcs_t *, elem_t, expr_t, error_t *);
char delimiter;
} body_t;
typedef struct
{
const char *name;
int priority;
body_t body;
} elem_info_t;
static const elem_info_t s_STD_UN_FUNC[] = {
{"sqrt", 2, sqrt},
{"sin", 2, sin},
{"cos", 2, cos},
{"tg", 2, tan},
和VS表示(强调功能分配)
错误C2440:“正在初始化”:无法从“double”(\uu)cdecl)转换
*)(双人)至“双人”
但所有类型的指针都已存在于union类型中。显式类型转换导致另一个错误。在这种情况下我该怎么办?谢谢。初始化联合时,如果您未指定哪个成员,默认情况下将初始化第一个成员。这就是错误的来源 您需要使用指定的初始值设定项来指定要设置的成员:
static const elem_info_t s_STD_UN_FUNC[] = {
{"sqrt", 2, { .UnFunc = sqrt}},
{"sin", 2, { .UnFunc = sin}},
{"cos", 2, { .UnFunc = cos}},
{"tg", 2, { .UnFunc = tan}},
...
发布的代码包含几个缺少的关键元素 下面显示了一种可接受的编写代码的方法
#include <math.h>
// set these following 5 typedefs to your actual types
typedef int error_t;
typedef int vars_t;
typedef int elem_t;
typedef int expr_t;
typedef int custom_funcs_t;
typedef union uFuncTypes
{
double value;
double (*UnFunc)(double);
double (*BiFunc)(double, double);
double (*VarAssi)(vars_t *, elem_t, elem_t, error_t *);
void (*FuncAssi)(custom_funcs_t *, elem_t, expr_t, error_t *);
char delimiter;
} body_t;
typedef struct funcStruct
{
const char *name;
int priority;
body_t body;
} elem_info_t;
static const elem_info_t s_STD_UN_FUNC[] = {
{ "sqrt", 2, .body.UnFunc = sqrt },
{ "sin", 2, .body.UnFunc = sin },
{ "cos", 2, .body.UnFunc = cos },
{ "tg", 2, .body.UnFunc = tan }
};
#包括
//将以下5个typedef设置为您的实际类型
typedef int error\u t;
typedef int vars\t;
类型定义内部元素;
typedef int expr\t;
自定义函数的类型定义;
typedef联合类型
{
双重价值;
双倍(*未融资)(双倍);
双人(*BiFunc)(双人,双人);
双(*VarAssi)(vars_t*、elem_t、elem_t、error_t*);
无效(*FuncAssi)(自定义函数*、元素、表达式、错误*);
字符分隔符;
}身体;
typedef结构funcStruct
{
常量字符*名称;
int优先级;
身体;
}元素信息;
静态常量信息标准函数[]={
{“sqrt”,2,.body.UnFunc=sqrt},
{“sin”,2,.body.UnFunc=sin},
{“cos”,2,.body.UnFunc=cos},
{“tg”,2,.body.UnFunc=tan}
};
注意:对于大多数调试器,为了正确显示结构和联合中的字段,需要在定义中包含适当的标记名
最新的C标准强烈建议不要在类型名称的末尾使用
\u t
,因为C喜欢为自己保留该结尾。请给出sqrt、sin等的定义。如果在您的联合中放入double(*UnFunc)(double),会发生什么代码>双值前面的第一个<代码>双值代码>?顺便说一句,我希望你有一个很好的理由使用联合。它们可能是有问题的(你的代码就是一个例子)。该位置的错误将消失,但在所有其他位置,由具有其他类型的函数定义的错误将保留。sqtr和其他来自数学。h发布的代码缺少类型的定义:elem\u t、Error\u t、expr\u t、custom\u funcs\t、,“body\u t”的typedef失败了。@evehor很高兴我能帮上忙。如果您觉得有用,请随时联系。谢谢。我会注意到你的话的。我们有c类教育课程。我们用c89写:)