在G ++ 4.4.7中"命名构造函数,而不是类型"

vil*_*apx 6 c++ gcc

我有以下简单的C++代码:

#include <cstdio>

class A
{
public:
    A(int y) : x(y) {}
    A& operator=(const A& rhs);
    int x;
};

A::A& A::operator=(const A& rhs) { this->x = rhs.x; return *this; }

int main(int, char**)
{
    A a1(5);
    A a2(4);

    printf("a2.x == %d\n", a2.x);

    a2 = a1;

    printf("a2.x == %d\n", a2.x);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

11号线,在定义Aoperator=()功能是,是畸形......或者,至少,我相信如此.正如预期的那样,G ++ 4.7.4以及我尝试过的每个较新版本的GCC都会引发以下错误:

main.cpp:11:1: error: ‘A::A’ names the constructor, not the type
Run Code Online (Sandbox Code Playgroud)

奇怪的是,G ++ 4.4.7成功地编译了这个程序,没有任何警告,甚至打印4和5,正如预期的那样,如果第11行被正确写入(即只是A&代替A::A&).

有人可以帮我解释G ++ 4.4.7究竟发生了什么吗?这只是该版本中的一个错误(虽然是一个非常古老的错误,但仍然使用它我们感到羞耻)?我认为标准将明确说明operator=()必须如何声明和定义函数.

das*_*ght 5

g ++中有一个相关的错误.它已在版本4.5.0中修复,因此4.4.7仍然有它.

这是错误描述:

cc1plus没有正确实现类名注入.特别是下面的剪切应该被拒绝,因为A :: A没有命名类型(它指定一个构造函数)

struct A { };

int main()
{
    A::A a;       // should be an ERROR
}
Run Code Online (Sandbox Code Playgroud)

尽管此错误的症状与您描述的内容不同,但在两种情况下,编译器A::A在实际命名构造函数时都将其视为类型名称.我很确定这两种行为具有相同的根本原因,这是4.5.0之前的范围解析执行不佳.