gcc 返回嵌套类错误
我尝试使用嵌套类的完全限定名称,如下所示,但编译器犹豫不决!
template <class T> class Apple {
//constructors, members, whatevers, etc...
public:
class Banana {
public:
Banana() {
//etc...
}
//other constructors, members, etc...
};
};
template <class K> class Carrot{
public:
//etc...
void problemFunction()
{
Apple<int>::Banana freshBanana = someVar.returnsABanana(); //line 85
giveMonkey(freshBanana); //line 86
}
};
我的问题是,编译器说:
Carrot.h:85: error: expected ';' before 'freshBanana'
Carrot.h:86: error: 'freshBanana' was not declared in this scope
我曾认为使用完全限定名称允许我访问这个嵌套类?它可能会打我的脸,但我到底在这里没看到什么?
I am attempting to use the fully qualified name of my nested class as below, but the compiler is balking!
template <class T> class Apple {
//constructors, members, whatevers, etc...
public:
class Banana {
public:
Banana() {
//etc...
}
//other constructors, members, etc...
};
};
template <class K> class Carrot{
public:
//etc...
void problemFunction()
{
Apple<int>::Banana freshBanana = someVar.returnsABanana(); //line 85
giveMonkey(freshBanana); //line 86
}
};
My issue is, the compiler says:
Carrot.h:85: error: expected ';' before 'freshBanana'
Carrot.h:86: error: 'freshBanana' was not declared in this scope
I had thought that using the fully qualified name permitted me to access this nested class? It's probably going to smack me in the face, but what on earth am I not seeing here??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能不是您在代码中所做的。错误消息看起来像你这样做
编译器在解析代码之前必须知道名称是否命名了类型。在这种情况下,当它解析时,它无法知道,因为
K
是什么类型,尚不知道(您可能有一个Apple
的专门化,但它不有那个嵌套类)。因此它假设Apple::Banana
不是一种类型。但是,它是一个表达式,后面需要一个运算符或分号。您可以通过插入
typename
来修复它:断言名称是一种类型,然后编译器知道将其解析为声明。
That's probably not what you do in your code. The error message looks like you do this
The compiler has to know before it parses the code whether a name names a type or not. In this case, when it parses, it cannot know because what type
K
is, is not yet known (you could have a specialization forApple<int>
that doesn't have that nested class). So it assumesApple<K>::Banana
is not a type. But then, it is an expression and an operator is needed after it or a semicolon.You can fix it by inserting
typename
:That asserts the name is a type, and the compiler then knows to parse this as a declaration.