gpt4 book ai didi

c++ - 避免在 C++ 中重新定义

转载 作者:行者123 更新时间:2023-11-28 07:40:25 24 4
gpt4 key购买 nike

我想避免从两个不同的包含文件重新定义,如下所示:

文件ABC.h

extern int v=1;

文件 foo.h

#include "ABC.h"
class Foo
#ifdef BLA
: public ABC
#endif

{
...
};

文件 bar.h

extern int v=3;

主要内容:

#define BLA
#include <foo.h>
#include <bar.h>

基本上foo是我写的类,bar是第三方库。但这似乎不起作用。我该如何解决这个问题?

抱歉,这有点难以描述,这个例子有点糟糕,因为冲突的部分实际上不是变量,而是像 #define 这样的东西,并且包裹在大块代码中(错误消息是: "`__vector_17' 的多重定义")。有没有办法不使用命名空间来解决它?

最佳答案

使用命名空间可以解决这个问题:

namespace foo
{
int val =1;
}

namespace bar
{
int val =3;
}

using namespace foo;

int x = val; //Now x will be assigned with 1

关于c++ - 避免在 C++ 中重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15935885/

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