G++ 4.4.7 中的"names the constructor, not the type"

"names the constructor, not the type" in G++ 4.4.7

本文关键字:the not type constructor names 中的 G++      更新时间:2023-10-16

我有以下简单的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 == %dn", a2.x);
    a2 = a1;
    printf("a2.x == %dn", a2.x);
    return 0;
}

第11行,其中Aoperator=()函数的定义已畸形...或者至少我相信。正如预期的那样,G 4.7.4以及我尝试过的每个较新版本的GCC都会引发以下错误:

main.cpp:11:1: error: ‘A::A’ names the constructor, not the type

奇怪的是,G 4.4.7成功编译了该程序,没有警告,甚至可以打印4和5,如果第11行正确编写(即仅使用A&而不是A::A&(。

(。 (。

有人可以帮助我解读G 4.4.7到底发生了什么?这只是该版本中的一个错误(尽管一个非常旧的错误,而我们仍在使用它(?我认为该标准将明确说明必须如何声明和定义operator=()功能。

g 中有一个相关的错误。它是在版本4.5.0中修复的,因此4.4.7仍然具有。

这是错误描述:

cc1plus不能正确实施类名注入。 特别是,以下剪切应根据 A :: A不命名类型(它指定构造函数(

struct A { };
int main()
{
    A::A a;       // should be an ERROR
}

尽管此错误的症状与您所描述的症状并不相同,但在两种情况下,编译器实际上将A::A视为类型名称,当它实际上命名构造函数时。我可以肯定的是,这两种行为具有相同的根本原因,这是版本4.5.0之前的范围分辨率的实现不佳。

在dasblinkenlight的正确答案上扩展 - C 03标准明确宣布他和我的代码在[class.qual]中:

如果 nested-name-depifier 提名为C类 在 nested-name-depifier 中指定的是在C中查找时,是 C的注射类名称为C(第9条(,该名称被视为 命名C类C的构造函数 仅在出现的构造函数定义的声明器-ID 中 在班级定义之外。[示例:

struct A { A(); };
struct B: public A { B(); };
A::A() { }
B::B() { }
B::A ba; // object of type A
A::A a;  // error, A::A is not a type name

- end示例]

相关文章: