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"
以下程序使用 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
。这就是为什么当你使用双括号时你会得到类似的行为:因为它是同一件事!
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- C++:离奇发生的"Request for member X of Y which is of non-class type Z"
- 链表函数 C++ "which is of non-class type 'int'" ?
- tbb::cache_aligned_allocator:与__m128i一起"request for member...which is of non-class type"。用户错误或错误?
- 了解 FTP 服务器项目的"create a virtual filesystem which allows mapping of arbitrary directories"
- 如何调试提升元组错误"no operator found which takes a left-hand operand of type"
- "error: request for member ‘size’ in ‘a’, which is of pointer type"但我不认为这是一个指针