【问题标题】:How can I convert optional parameter method declared in C into c++如何将 C 中声明的可选参数方法转换为 C++
【发布时间】:2017-02-02 09:56:34
【问题描述】:

我正在将一些旧的 C 代码转换为 c++ 并遇到一些奇怪的东西,在 .h 文件中声明的 C 代码说: void Message(char *s, ...); .c 中的实现负责人

void Message(char *s, long x1, long x2, long x3, long x4, long x5, long x6, long x7, long x8, long x9, long x10){...}

当我将“直接”复制到 C++ 中的类声明和实现中时,我得到“原型错误”。

我是否需要像在 .c 文件中一样进行完整的声明,或者是否有另一种方式用于 c++ 和类的使用? x1 ... x10 是选项参数,很少使用。

使用 g++ 和 NetBeans 7.3 在 linux 中工作

【问题讨论】:

  • 确实了解 C++ 中的默认参数吗?如果没有,那么我建议你 find a good beginners book 并阅读它。
  • 这段 C 代码只是喜欢它未定义的行为,不是吗?
  • 这仅在 C 中“有效”(使用非常松散的术语),因为 C 不会将参数类型编码为依赖于实现的重整名称,并且您对调用者使用了从左到右的调用约定-cleanup 用于传递的参数。 C++ 在这方面要严格得多,很多。您仍然可以使用变量参数(请参阅 Groben 的链接),但不能做这样的事情并期望它能够工作(老实说,您一开始就不想这样做)。
  • 省略号并不真正意味着“可选”。实现... 的函数应该使用<stdarg.h> 工具(va_startva_arg 等)来检索那些尾随参数。连C++都有...,所以...和可选参数是有区别的。

标签: c++ c optional-parameters


【解决方案1】:

C 代码不应编译。要在 C++ 中实现可选参数,请将它们的值放在声明中:

void Message(char *s, long x1 = 0L, long x2 = 0L, long x3 = 0L, long x4 = 0L, long x5 = 0L,
        long x6 = 0L, long x7 = 0L, long x8 = 0L, long x9 = 0L, long x10 = 0L);

然后像这样定义你的函数:

void Message(char *s, long x1, long x2, long x3, long x4, long x5,
        long x6, long x7, long x8, long x9, long x10)
{
    // Function body
}

请注意,您只需在一处指定默认值。在声明中执行此操作,以便它们对客户可见。

【讨论】:

  • 感谢 Martin,我实施了您的建议并为我解决了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2020-09-04
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
相关资源
最近更新 更多