来自不同库的同名类和宏

问题描述 投票:0回答:2

我在我的项目中使用了 2 个库。一个定义了

Status
宏,另一个在命名空间中有一个名为
Status
的类。

在代码中使用

Status
类时遇到问题:

// first library
namespace Test {
    class Status {};
}

// second library
#define Status int

// my code
int main() {
    Test::Status test;
    return 0;
}

错误:

error: expected unqualified-id before ‘int’
    8 | #define Status int

如何在我的项目中使用这两个库?

c++ libraries
2个回答
10
投票

如果您不需要使用第二个库定义的

Status
宏,那么您可以尝试以下操作:

#include <second-library.h>
#undef Status
#include <first-library.h>

如果您希望能够使用第二个库定义的

Status
宏,您可以尝试以下操作:

#include <second-library.h>
using Status2 = Status;
#undef Status
#include <first-library.h>

然后将其用作

Status2
而不是
Status


0
投票

代码编译

namespace Status {
    class Test();
}
  • 创建一个名为“Status”的库
  • 在“Status”中创建测试类

#define Status int

  • 将所有出现的单词 Status 替换为 int

Test::Status test;

  • 在主函数内创建一个测试对象

这里存在冲突,因为您将 Status[word] 更改为 int,这会将以下语句

Test::Status test;
转换为此
Test::int test;

所以要解决这个问题你有很多选择

通过以下命令取消状态字的定义

#undef Status

通过以下命令为宏 int 使用另一个关键字

#define integer int

创建头文件“filename.h”并放入以下代码 文件中的

namespace Test { class Status(); }
#include <filename.h>
其扩展名为 .cpp,并确保您在工作目录中创建了 filename.h。

我希望这对你有帮助..

© www.soinside.com 2019 - 2024. All rights reserved.