gpt4 book ai didi

在 C 中调用不带括号的参数的函数?

转载 作者:行者123 更新时间:2023-12-03 22:58:27 27 4
gpt4 key购买 nike

当一个函数没有任何参数时,可以通过 define 不带括号地调用它作为

#define test test()

是否可以在没有括号的情况下调用带参数的函数?就像是
#define test test(char *arg)

test "argument 1";

最佳答案

这在 C 中是不可能的。标准 (C99) 的 §6.5.2 描述了后缀表达式,并且没有类似的语法。函数调用是(第 6.5.2.2 节):

A postfix expression followed by parentheses () containing a possibly empty, comma-separated list of expressions is a function call. The postfix expression denotes the called function. The list of expressions specifies the arguments to the function.



括号不是可选的,它们需要包装所有参数,因此您需要一个类似函数的宏(在“调用”站点需要括号)或两个单独的东西(一个插入起始括号,一个插入结束一)。

你可以这样做:
#define test puts(
#define end );
#define int_proc int
#define proc_body {
#define proc_end }
#define no_args (void)
#include <stdio.h>

int_proc main no_args
proc_body
test "hello" end
proc_end

但是……真的吗?

C++ 提供了更多的可能性,尤其是运算符重载。如果您想“自定义”某些语法,您可能需要研究一下。

这是一个可怕的例子:
#include <iostream>

struct Foo {
void operator=(char const* str)
{
std::cout << str << std::endl;
}
};
Foo global_foo;

#define test global_foo =

int main()
{
test "hello";
}

请注意,有些合理的方法您可能会觉得有吸引力,例如Qt的 qDebug实用程序类。示意性地,它是这样的:
#include <iostream>

struct debug {
debug() {}
~debug()
{
std::cout << std::endl;
}
debug const& operator<<(char const* msg) const
{
std::cout << msg << " ";
return *this;
}
};

通常的使用方法是:
debug() << "this" << "works";

如果你添加一个接受 char const* 的构造函数:
debug(char const*msg)
{
std::cout << msg << " ";
}

然后你可以使用转换符号并写:
(debug) "Hello";

这与您拥有的非常接近(并且是可宏的)。

然后你可以喜欢所有其他运算符( operator, 将是主要候选者),但优先规则可能会破坏乐趣。

关于在 C 中调用不带括号的参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18348620/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com