gcc 返回嵌套类错误

发布于 2024-08-26 16:17:10 字数 743 浏览 3 评论 0原文

我尝试使用嵌套类的完全限定名称,如下所示,但编译器犹豫不决!

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

允世 2024-09-02 16:17:10

这可能不是您在代码中所做的。错误消息看起来像你这样做

Apple<K>::Banana freshBanana = someVar.returnsABanana();

编译器在解析代码之前必须知道名称是否命名了类型。在这种情况下,当它解析时,它无法知道,因为 K 是什么类型,尚不知道(您可能有一个 Apple 的专门化,但它不有那个嵌套类)。因此它假设 Apple::Banana 不是一种类型。但是,它是一个表达式,后面需要一个运算符或分号。

您可以通过插入 typename 来修复它:

typename Apple<K>::Banana freshBanana = someVar.returnsABanana();

断言名称是一种类型,然后编译器知道将其解析为声明。

That's probably not what you do in your code. The error message looks like you do this

Apple<K>::Banana freshBanana = someVar.returnsABanana();

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 for Apple<int> that doesn't have that nested class). So it assumes Apple<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:

typename Apple<K>::Banana freshBanana = someVar.returnsABanana();

That asserts the name is a type, and the compiler then knows to parse this as a declaration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文