Use of undeclared identifier in C++ with templates and inheritance [duplicate]

感情迁移 提交于 2019-12-30 05:57:08

问题


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:

  1. Missing semicolons after class definitions.
  2. Missing type for doSomething method declaration/definition.
  3. Missing type for definition of addStuff method.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!