问题
The following code cannot compile - use of undeclared identifier. I use GCC and XCode for compilation.
Everything is in a single header file.
include "MyArray.h"
template <typename T>
class MyBase {
public:
MyBase();
virtual ~MyBase();
void addStuff(T* someStuff);
protected:
MyArray<T*> stuff;
};
template <typename T>
MyBase<T>::MyBase() {}
template <typename T>
MyBase<T>::~MyBase() {}
template <typename T>
void MyBase<T>::addStuff(T* someStuff) {
stuff.add(someStuff);
}
// ---------------------
template <typename T>
class MyDerived : public MyBase<T> {
public:
MyDerived();
virtual ~MyDerived();
virtual void doSomething();
};
template <typename T>
MyDerived<T>::MyDerived() {}
template <typename T>
MyDerived<T>::~MyDerived() {}
template <typename T>
void MyDerived<T>::doSomething() {
T* thingy = new T();
addStuff(thingy); //here's the compile error. addStuff is not declared.
}
Does anyone have an explanation? Thanks in advance!
回答1:
try
this->addStuff(thingy);
回答2:
There are several issues:
- Missing semicolons after class definitions.
- Missing type for
doSomethingmethod declaration/definition. - Missing type for definition of
addStuffmethod.
After fixing that it seems to work.
Edit: As you have fixed the syntax errors and it still does not work. As others have suggested your compiler may require you to call the addStuff method with this-> prefix:
this->addStuff(thingy);
回答3:
It's due to template inheritance. In such case you should mannualy specify using for base methods:
template <typename T>
MyDerived<T>::doSomething() {
using MyBase<T>::addStuff;
T* thingy = new T();
addStuff(thingy);
}
or do it by this pointer:
template <typename T>
MyDerived<T>::doSomething() {
T* thingy = new T();
this->addStuff(thingy);
}
回答4:
use this pointer to invoke the addStuff method i.e
this->addStuff(thingy);
来源:https://stackoverflow.com/questions/10735611/use-of-undeclared-identifier-in-c-with-templates-and-inheritance