C ++:“对于非类类型Z的Y的成员X的请求”的异常出现。 [英] C++: bizarre occurrence of "Request for member X of Y which is of non-class type Z"

查看:217
本文介绍了C ++:“对于非类类型Z的Y的成员X的请求”的异常出现。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用g ++ 4.6编译的以下程序产生在'a2'中成员'y'的错误

The following program, compiled with g++ 4.6, yields the error

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



<

at its last line:

#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的构造函数的参数解决了问题。

As can be seen from the working variant included in the code, adding parentheses around the arguments of the constructor of A solves the problem.

我已经看到一些由构造函数调用解释为一个函数声明引起的相关错误,就像创建一个没有参数的对象的构造函数, :

I have seen some related errors caused by a the interpretation of a constructor invocation as a function declaration, like when creating an object with no argument to its constructor, but with braces:

myclass myobj();

但我认为

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

不能解释为函数声明。

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

Someone can explain to me what is happening?

推荐答案

其中编译器解释 A< B> a2(B(v))作为函数的声明。例如:

It's a case of most vexing parse where the compiler interprets A<B> a2(B(v)) as the declaration of a function. Such that:

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

v 是参数名称

A<B> is the return type
a2 is the function name
B is the type of the argument
v is the argument name

p>

So, when you are doing

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

编译器不会考虑 a2.yu 作为类,这就是为什么你得到非类类型错误。

The compiler does not think of a2.y.u as a class, that's why you are getting the non-class type error.

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

Also, since double parenthesis aren't allowed in a function declaration, the version A<B> a2((B(v))); works because the compiler doesn't interprets it as a function declaration anymore, but as a variable declaration.

这篇关于C ++:“对于非类类型Z的Y的成员X的请求”的异常出现。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆