C++:离奇发生的"Request for member X of Y which is of non-class type Z"

C++: bizarre occurrence of "Request for member X of Y which is of non-class type Z"

本文关键字:of which is type non-class member for Request C++      更新时间:2023-10-16

以下程序使用 g++ 4.6 编译,产生错误

request for member ‘y’ in ‘a2’, which is of non-class type ‘A<B>(B)’

在最后一行:

#include <iostream>
template <class T> class A
{
public:
  T y;
  A(T x):y(x){}
};
class B
{
public:
  int u;
  B(int v):u(v){}
};
int main()
{
  int v = 10;
  B b1(v);
  //works
  A<B> a1(b1);
  //does not work (the error is when a2 is used)
  A<B> a2(B(v));
  //works
  //A<B> a2((B(v)));
  std::cout << a1.y.u << " " << a2.y.u << std::endl;    
}

从代码中包含的工作变体可以看出,在 A 构造函数的参数周围添加括号可以解决问题。

我已经看到了一些由将构造函数调用解释为函数声明引起的相关错误,例如在创建对象时,其构造函数没有参数,但带有大括号:

myclass myobj();

但在我看来,

A<B> a2(B(v));

不能解释为函数声明。

有人可以向我解释发生了什么?

这是

编译器将A<B> a2(B(v))解释为函数声明的最令人烦恼的解析情况。这样:

返回类型
A<B> a2是函数名称
B是参数
的类型 参数名称
v

所以,当你在做

std::cout << a1.y.u << " " << a2.y.u << std::endl;

编译器不会将a2.y.u视为类,这就是您收到non-class type错误的原因。

此外,由于函数声明中不允许使用双括号,因此版本A<B> a2((B(v)));有效,因为编译器不再将其解释为函数声明,而是解释为变量声明。

我认为您正在被"最烦人的解析"所困扰,这意味着A<B> a2(B(v));被解析为函数声明而不是变量声明。

它是一个

函数声明:

A<B> a2(B(v));
//is same as:
A<B> a2(B v);
//consider:
int foo(int v);
int foo(int (v));

如以下代码示例所示:

int a (int(v)) {
    return v;
}
int main() {
    std::cout << a(5); //prints 5
}

这句话确实是一个宣言。在此示例中,参数的类型为 int,名为 v 。将其与您的代码相关联,该参数的类型为 B,名为 v 。这就是为什么当你使用双括号时你会得到类似的行为:因为它是同一件事!