I'm new to C++, so bear with me. I have a generic class called A. A has a nested class called B. A contains a method called getB(), which is supposed to return a new instance of B. However, I can't get my code to compile. Here's what it looks like:#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();
}
When I try to compile this, I get the following error:
error: expected constructor, destructor, or type conversion before '*' token
Does anybody know what I'm doing wrong?
Thanks,
helixed
UPDATE:
Thanks for the quick replies everyone. I'm still having a little trouble getting this working. After taking the suggestions listed here, I have something like this:
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 {
};
However, when I try to use this from main, I get an error. Here's my main method:
main.cpp
#include "A.h"
int main(int argc, char *argv[])
{
A<C> *a = new A<C>();
A<C>::B *b = a.getB();
}
When I try to compile this, I get the following error:
error: request for member 'getB' in 'a', which is of non-class type 'A<C>*'
Thanks again for the quick responses.
helixed
The compiler isn't smart enough to figure that "B" is a type when "A" is templated. Try using typename.
template <class E>
typename A<E>::B * A<E>::getB() {
return new B();
}
You need to use typename
in your definition to hint to the compiler that B is a type.
template <class E>
typename A<E>::B * A::getB() {
return new B;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With