从通用外部类返回指向嵌套内部类的指针

时间:2010-04-06 19:12:27

标签: c++ templates nested-class

我是C ++的新手,所以请耐心等待。我有一个名为A的泛型类.A有一个名为B的嵌套类.A包含一个名为getB()的方法,该方法应该返回B的新实例。但是,我无法获取我的代码进行编译。这是它的样子:#include

A.H

template <class E>
class A {

public:
    class B {
    public:
        int data;
    };

    B * getB(); 
};

A.cpp

#include "A.h"

template <class E>
A<E>::B * A::getB() {
    return new B();
}

当我尝试编译时,我收到以下错误:

error: expected constructor, destructor, or type conversion before '*' token

有人知道我做错了吗?

谢谢,

helixed

更新:

感谢大家的快速回复。让这个工作起来我还有点麻烦。在采取此处列出的建议后,我有这样的事情:

A.H

template <class E>
class A {

public:
    class B {
    public:
        int data;
    };

    B * getB(); 
};

template <class E>
typename A<E>::B * A<E>::getB() {
    return new B();
}

class C {

};

然而,当我尝试从main使用它时,我收到一个错误。这是我的主要方法:

的main.cpp

#include "A.h"

int main(int argc, char *argv[])
{
    A<C> *a = new A<C>();
    A<C>::B *b = a.getB();
}

当我尝试编译时,我收到以下错误:

error: request for member 'getB' in 'a', which is of non-class type 'A<C>*'

再次感谢您的快速回复。

helixed

3 个答案:

答案 0 :(得分:7)

当“A”被模板化时,编译器不够聪明,无法确定“B”是一种类型。尝试使用typename。

template <class E>
typename A<E>::B * A<E>::getB() {
    return new B();
}

答案 1 :(得分:2)

您需要在定义中使用typename来向编译器提示B是一个类型。

template <class E>
typename A<E>::B * A::getB() {
   return new B;
}

答案 2 :(得分:0)

回答更新:

你不需要new C ++中的所有东西,事实上,如果你没有,那将是最好的,因为那时你必须明确delete分配的内存或使用智能指针。

所以,这是你修改的代码:

template <class E>
class A {

public:
    class B {
    public:
        int data;
    };

    B getB(); // Object, not pointer
};

template <class E>
typename A<E>::B A<E>::getB() {
    return B();
}

#include "A.h"

int main(int argc, char *argv[])
{
    A<C> a = A<C>();
    A<C>::B b = a.getB();
}

如果您希望new A<C>类,那么您需要使用operator->来调用方法:

A<C>::B b = a->getB();