我有 SuperClass 和 Subclass 类,其中 SubClass 继承自 SuperClass。
在 SuperClass 中,我有一个常量属性,其值取决于使用它的子类。但是我需要在 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
子类.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>
错误。 可能是什么问题?
最佳答案
问题是您对 NULLPOSITION
的定义。您已经为模板 SuperClass
声明了一个静态成员 NULLPOSITION
,但尚未定义它。相反,您尝试定义成员以对其进行部分显式实例化。您应该删除部分显式实例化定义,并为 NULLPOSITION
定义常规模板类静态成员定义。
要允许子类为 NULLPOSITION
提供不同的初始化值,这可以通过(可能是可选的)模板参数来实现。
template <class T, class P, P INIT>
class SuperClass
{
public:
typedef T type;
typedef P position;
static const position NULLPOSITION;
};
template<class T, class P, P INIT>
const typename SuperClass<T,P,INIT>::position
SuperClass<T,P,INIT>::NULLPOSITION = INIT;
template <class T>
class SubClass:public SuperClass<T,int, 0>
{
};
关于C++ - 未定义类型的无效使用... - `class 的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517920/