gpt4 book ai didi

c++ - 在 C++ 中使用反斜杠定义函数

转载 作者:行者123 更新时间:2023-11-30 02:35:36 26 4
gpt4 key购买 nike

我看到人们在宏中定义函数时使用反斜杠:

#define ClassNameNoDebug(TypeNameString)                                    \
static const char* typeName_() { return TypeNameString; } \
static const ::Foam::word typeName

我做了一个非常简单的测试。但是我遇到了一堆错误。测试代码如下:在我的 testmacro.h 文件中:

#define declearlarger(first,second)                                                          \
double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}

在我的 main() 函数中:

int second =2;
int first =1;

cout << declearlarger(first,second) << endl;

错误是:

/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected primary-expression before 'double'
double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}
^
/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected ';' before 'double'
double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}
^
/home/jerry/Desktop/backslash/backslash_test/main.cpp:24: error: expected primary-expression before '<<' token
cout << declearlarger(first,second) << endl;
^

这就是我所有的测试错误。谁能给出一些建议,为什么会弹出这些错误?

最佳答案

您正在尝试在表达式中使用函数定义(由您的宏生成)。 C++ 不允许这样的事情。您可以将宏定义为

#define declearlarger(first,second) \
(((first)>(second)) ? (first) : (second))

然后就可以了。另请注意,没有任何错误来自反斜杠,它们都是由于函数定义/表达式冲突而产生的。

关于c++ - 在 C++ 中使用反斜杠定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33445981/

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