C++ 11标准的7.1.3[9]部分指出:



[示例:

typedef struct { } *ps, S; // S is the class name for linkage purposes

—结束示例]

这意味着在以下示例中,Foo应该用作未命名类的名称,并在以下示例中用于链接目的:
//foo1.cpp
typedef class
{
        public: int f();
} Foo;

int Foo::f()
{
        return 5;
}

由于Foo::f()是在foo1.cpp中定义的,因此编译器不应抱怨。
//foo2.cpp
typedef class
{
    public: int f();
} Foo;

Foo foo;

int main()
{
    return foo.f();
}

但是,我收到GCC 4.8的链接错误。我想念什么吗?
$g++ foo1.cpp foo2.cpp
/tmp/ccMwHawT.o: In function `main':
713Y51.cpp:(.text+0x24): undefined reference to `Foo::f()'
collect2: error: ld returned 1 exit status

最佳答案

我想你是正确的。除了您已经在问题中提出的内容之外,从标准中真正添加的没有其他内容。

这是GCC中的long-standing bug。 clang同意您的解释并接受您的程序。

关于c++ - 当typedef声明定义未命名类时链接失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25898127/

10-10 00:44
查看更多