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

#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/

10-11 21:29