在基础类问题上返回带有模板的嵌套类

在基础类问题上返回带有模板的嵌套类

本文介绍了C ++在基础类问题上返回带有模板的嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个列表对象,并将迭代器类嵌套在其中以了解其工作方式.在某些方法中,我试图返回一个迭代器对象,但是它不起作用.我创建了一个示例来显示问题:

I am trying to create a list object, with the iterator class nested inside to understand how it works.In some method, I am trying to return an iterator object but it doesn't work.I created an example to show the problem :

// CLASS A
template <class T>
class A
{
    public:
        class B;
        A(){}
};

// CLASS B
template <class T>
class A<T>::B
{
    private:
        int varB;

    public:
        B(B& b);
        B(const int&);
        B returnThis();
};

template <class T>
A<T>::B::B(const int& value)
{
    varB = value;
}

template <class T>
A<T>::B::B(B& b)
{
    varB = b.varB;
}

template <class T>
A<T>::B A<T>::B::returnThis()
{
    return *this;
}

// MAIN

void main()
{
    A<int>::B classB(10);
}

错误在那些行附近:

template <class T>
A<T>::B A<T>::B::returnThis()

编译器告诉我我缺少一个;在A :: B :: returnThis()之前

The compiler tells me I am missing a ; before A::B::returnThis()

我试图解决这个问题好几天了,但我找不到使它工作的方法...我真的很感谢您的帮助.预先感谢!

I am trying to solve this problem for days and I can't find a way to make it work...I would really appreciate some help.Thanks in advance!

推荐答案

您需要 typename :

typename A<T>::B

向编译器指示 A&T; :: B 是一种类型.这是一个很好的解释原因.

To indicate to the compiler that A<T>::B is a type. Here's a good explanation why.

什么是 B 取决于什么 A< T> ,这称为依赖关系.每当您从类或结构中获取类型并且它依赖于模板时,就需要使用 typename .

What B is depends on what A<T> is, this is called dependency. Any time you are getting a type out of a class or struct, and it's dependent on a template, you'll need to use typename.

这篇关于C ++在基础类问题上返回带有模板的嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:47