从无名命名空间外部定义函数

huangapple go评论71阅读模式
英文:

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.oA2.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 &lt;&lt; &quot;hello from A1&quot;;
    }

A2.cpp
    A::A()
    {
        std::cout &lt;&lt; &quot;hello from A2&quot;;
    }

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.

huangapple
  • 本文由 发表于 2023年5月13日 20:31:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定