预处理器 ## 粘贴运算符
Preprocessor ## pasting operator
我试图实现的是创建代码中提到的这三个类,但只是尝试方便地使用预处理器,以便可以创建和执行这些类似的类,而不是为它们编写单独的代码:
#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 并且不鼓励使用宏。您最好使用模板或传统的动态代码(根据您的需求)。与宏相比,模板在编译时引入了额外的类型检查,并提供更具可读性的错误消息。
您提出的宏解决方案是我以前使用过的解决方案,但我会以不同的方式看待这个问题。 宏解决方案是一个笨拙且难以维护和调试的所有代码,除了最琐碎的代码。
您是否考虑过从模板生成所需的代码? 使用 Cheetah 或 Mako 填写源模板会更简洁,您可以从配置文件驱动生成,因此您不必手动维护您的类列表。
你会有一个myclass.tmpl模板文件,看起来像这样:
#for len, baselen in enumerate(mylist_of_classes_i_want_to_generate)
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;
}
};
#end for
然后,在编译之前,在生成流开始时调用 cheetah 自动生成代码。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 预处理器:插入结构名称中的前一个行号
- 如何在c++中实现处理器调度模拟器
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 预处理器是否可以更改运算符重载功能的符号?
- 预处理器双哈希(##)运算符,如何连接变量值
- 在 Clang 中使用 MSVC 预处理器'charizing'运算符
- 是具有多核处理器的 c++ 运算符 |= 原子
- 预处理器 ## 粘贴运算符
- 反向预处理器字符串化运算符
- C++预处理器和运算符+重载
- 如何在不使用宏预处理器的情况下使用"<<"运算符传递多字符串
- 在 C++ 中创建带/不带预处理器的新运算符