gpt4 book ai didi

c++ - 预处理器##粘贴运算符

转载 作者:太空宇宙 更新时间:2023-11-04 16:18:33 25 4
gpt4 key购买 nike

我想要实现的是创建代码中提到的这三个类,但只是尝试使用方便的预处理器,以便可以创建和执行这些类似的类,而不是为它们编写单独的代码:

#include <iostream>
#define MYMACRO(len,baselen)
using namespace std;

class myclass ## len
{
int MYVALUE ## baselen;
public:
myclass ## len ## ()
{
cout << endl;
cout << " For class" ## len ## "'s function 'myFunction" ## len ## "' the value is: " << MYVALUE ## baselen << endl;
}
};

int main()
{
MYMACRO(10,100)
//myclass10 ob1;
MYMACRO(20,200)
//myclass20 ob2;
MYMACRO(30,300)
//myclass30 ob3;

myclass10 ob1;
myclass20 ob2;
myclass30 ob3;

cout << endl;

return 0;
}

现在我不知道是否可以完成 & 因为我收到此错误。如果是,请有人解决错误并启发我,如果不是,请给出相同的原因,这样我也可以放心我们在同一页面上!错误是:

[root@localhost C++PractiseCode]# g++ -o structAndPreprocessor structAndPreprocessor.cpp
structAndPreprocessor.cpp:5: error: invalid token
structAndPreprocessor.cpp:6: error: invalid function declaration
structAndPreprocessor.cpp:7: error: invalid token
structAndPreprocessor.cpp:9: error: invalid token
structAndPreprocessor.cpp:9: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp: In function `int main()':
structAndPreprocessor.cpp:25: error: `myclass10' was not declared in this scope
structAndPreprocessor.cpp:25: error: expected `;' before "ob1"
structAndPreprocessor.cpp:26: error: `myclass20' was not declared in this scope
structAndPreprocessor.cpp:26: error: expected `;' before "ob2"
structAndPreprocessor.cpp:27: error: `myclass30' was not declared in this scope
structAndPreprocessor.cpp:27: error: expected `;' before "ob3"
[root@localhost C++PractiseCode]#

最佳答案

您需要在行的每一端使用 \ 来定义您的宏(并且可能从宏中删除 using 语句)

using namespace std;

#define MYMACRO(len,baselen) \
class myclass ## len \
{ \
int MYVALUE ## baselen; \
(...snip...) \
}\
};

注意最后一行没有转义

您很可能正在执行 Cpp 并且不鼓励使用宏。您最好使用模板或传统的动态代码(取决于您的需要)。与宏相比,模板在编译时带来了额外的类型检查,并提供了更具可读性的错误消息。

关于c++ - 预处理器##粘贴运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19830742/

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