gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:05 24 4
gpt4 key购买 nike

我有以下简单的 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;
}

第 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=() 函数。

最佳答案

有一个related bug in g++ .它在 4.5.0 版本中已修复,因此 4.4.7 仍然存在。

错误描述如下:

cc1plus does not implement the class name injection correctly. In particular the snipped below should be rejected on the basis that A::A does not name a type (it designates a constructor)

struct A { };

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

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

关于c++ - G++ 4.4.7 中的 "names the constructor, not the type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44295575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com