我有類SuperClass和Subclass,其中SubClass從SuperClass繼承。C++ - 無效使用未定義的類型... - 類的聲明
在SuperClass中我有一個常量屬性誰的值取決於使用它的子類。 Howerver我需要它在SuperClass中聲明,因爲在SuperClass中還有一些其他方法也使用它,但是我需要在SubClass中初始化它,因爲常量的值根據實例化的SubClass類型而改變。
從previous question on SO,我知道最好的解決方案是使用特質類。然而,使用這樣的解決方案將涉及到我的代碼的巨大變化。因此,我選擇了這裏顯示的方法。
SuperClass.h
#ifndef SUPERCLASS_H
#define SUPERCLASS_H
#include <string>
template <class T, class P>
class SuperClass
{
public:
typedef T type;
typedef P position;
static const position NULLPOSITION;
};
#endif
SubClass.h
#ifndef SUBCLASS_H
#define SUBCLASS_H
#include <string>
#include "SuperClass.h"
template <class T>
class SubClass:public SuperClass<T,int>
{
};
template<class T>
const typename SuperClass<T,int>::position SuperClass<T,int>::NULLPOSITION=0;
#endif
的main.cpp
#include <cstdlib>
#include <iostream>
#include "SubClass.h"
using namespace std;
int main(int argc, char *argv[])
{
SubClass<int> subClass;
system("PAUSE");
return EXIT_SUCCESS;
}
在編譯我得到
invalid use of undefined type `class SuperClass<T, int>
和
declaration of `class SuperClass<T, int>
錯誤。 可能是什麼問題?
請請請請不要致電您的班級。 – Borgleader
@Borgleader(更好地稱之爲'class class','struct class','class struct'或'struct struct',對吧?:P) – 2013-08-29 18:01:35
@Borgleader好吧,我已經編輯了相應的問題。 – geraldCelente