【发布时间】:2020-08-21 15:12:34
【问题描述】:
我需要知道我可以在 C++ 中使用 'using' 关键字的范围。
假设我们在同一个代码库中有两个 CPP 文件,它们使用了具有相同类型名称的 'using' 关键字。
A.cpp
#include <iostream>
namespace space_A
{
typedef struct myStruct
{
int a;
myStruct(): a(1) {}
} MyStruct;
}
using my_type = space_A::MyStruct;
void func_A()
{
my_type *t_a = new my_type();
std::cout<<t_a->a;
}
B.cpp
#include <iostream>
namespace space_B
{
typedef struct myStruct
{
char *b;
myStruct(): b((char*)"xyz") {}
} MyStruct;
}
using my_type = space_B::MyStruct;
void func_B()
{
my_type *t_b = new my_type();
std::cout<<t_b->b;
}
这两个文件上的那些“using my_type = ....”行(实际上是针对使用点-(func_a, func_b))会不会有冲突? 简单地说,'my_type' 是各自文件范围的本地吗?
【问题讨论】:
-
typedef struct myStruct-- 在 C++ 中,typedef struct不是必需的。只需struct myStruct即可。 -
好的,但我在这里关注的是“使用 my_type=..”。例如:A.cpp 中的“my_type”能否在 B.cpp 的 func_B 中可见?
-
不,仅当
using在头文件中时。在不同的cpp文件上你是安全的。如果您不确定这样的问题,您可以随时将其写在您的代码中并检查您是否遇到任何错误。 -
@רועיאבידן 这通常是一种很好的做法,但编译器可能无法诊断诸如 ODR 违规之类的事情,这在这种情况下是可能的。
-
我们可以使用 'static' 关键字来声明文件本地的函数(在 C 中)。我需要这种“使用 my_type =....”的行为(如果我在文件 A.cpp 中使用 my_type,那么 my_type 必须是 A.cpp 的那个)。现在这些文件中是否存在这种行为?