英文:
Defining functions from nameless namespace outside the namespace
问题
如果我在一个无名称的命名空间内声明一个类,但在该无名称的命名空间之外定义成员函数,像这样:
A.hpp:
namespace {
struct A{
A();
};
}
A1.cpp:
A::A()
{
std::cout << "hello from A1";
}
A2.cpp:
A::A()
{
std::cout << "hello from A2";
}
在链接时,已定义的函数是否对其他翻译单元可见?如果我将A1.o
和A2.o
链接到一个可执行文件中,是否违反了ODR规定?
英文:
If I declare a class inside a nameless namespace, but define the member functions outside that nameless namespace, like so:
A.hpp:
namespace {
struct A{
A();
};
}
A1.cpp:
A::A()
{
std::cout << "hello from A1";
}
A2.cpp
A::A()
{
std::cout << "hello from A2";
}
will the defined functions be visible from other translation units during linking? Am I violating the ODR if I link A1.o
and A2.o
into one executable?
答案1
得分: 1
A
具有内部链接,因为它属于一个无名命名空间。因此,它的所有成员函数,包括A::A
,也具有内部链接。无法更改这一点,不论您在何处声明(或定义)成员函数,也不论频率。成员函数的链接性始终由它们所属的类的链接性确定。
英文:
A
has internal linkage because it belongs to an unnamed namespace. All its member functions, including A::A
, consequently also have internal linkage. There is no way to change that and it is not dependent on how often or where you declare (or define) the member functions. The linkage of member functions is always derived from the linkage of the class they belong to.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论