【问题标题】:C++ typedef function pointer and declare a pointer in one statementC++ typedef函数指针并在一个语句中声明一个指针
【发布时间】:2017-08-14 07:24:46
【问题描述】:

我有一个 c++ 程序,它可以导入一个包含很多函数的 dll。

//.h file

/*Description: set velocity(short id of axis, double velocity value)*/
typedef short(__stdcall *GT_SetVel)(short profile, double vel);
//.cpp file

/*Description: set velocity(short id of axis, double velocity value)*/
GT_SetVel SetAxisVel = NULL;
...
SetAxisVel = (GT_SetVel)GetProcAddress(GTDLL, "_GT_SetVel@10");
...
SetAxisVel(idAxis, vel);

我想让它更紧凑,比如

//.h file

/*Description: set velocity(short id of axis, double velocity value)*/
typedef short(__stdcall *GT_SetVel)(short profile, double vel) SetAxisVel = NULL;
//.cpp file

SetAxisVel = (GT_SetVel)GetProcAddress(GTDLL, "_GT_SetVel@10");
...
SetAxisVel(idAxis, vel);

这听起来很荒谬。有没有类似上面的语法,两个语句合并为一个,而不是放在一起放到相邻的行中。

原因是
(1) 我需要类型别名和函数指针变量,
(2) 并且必须有 typedef 的描述注释(语义通过参数列表进行参数描述)和指针声明(提供智能感知供以后使用)。

但是类型别名只使用一次,在两个不同的地方插入相同的描述似乎是多余的。

有没有办法让它更紧凑?谢谢。

【问题讨论】:

  • 据我了解,您想用 typedef 的类型声明变量并通过一个声明对其进行初始化。不,你不能用 typedef 处理它。但是如果你的变量是静态的或外部的,你就不需要初始化它。
  • 类型别名和变量是不同种类的元素。我认为向每个插入两个不同的 cmets 没有任何问题。

标签: c++ function-pointers intellisense typedef


【解决方案1】:

去掉 typedef,你可以缩短为:

// .cpp

/*Description: set velocity(short id of axis, double velocity value)*/
short(__stdcall *SetAxisVel)(short profile, double vel) = NULL;


SetAxisVel = reinterpret_cast<decltype(SetAxisVel)>(GetProcAddress(GTDLL, "_GT_SetVel@10"));

【讨论】:

  • 但是在头文件中定义变量存在问题,导致多重定义(LNK2005)错误。
  • 你需要把它放在页眉吗?你的第一个 sn-p 没有。
  • 我只想将所有描述包含在一个单独的文件中。
  • “类型别名只使用一次”,所以我把它去掉了,所以现在所有代码都在同一个cpp文件中。
猜你喜欢
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多