我有这个代码:
在 ah 文件中:
#ifndef A_H_
#define A_H_
class Class_Hierarchy{
public:
std::map<const Type*, std::set<const Type*>> map;
Class_Hierarchy(){
std::map<const Type*, std::set<const Type*>> map;
}
};
template<class T>
class BASE_Polymorphic {
friend T; //only the actual type can register this class at the CASTS data structure.
private:
void Register_Inheritence(const Type *base);
public:
virtual ~OOP_Polymorphic() {}
static const Type *Get_Type();
virtual const Type *My_Type();
};
class CASTS{
private:
static Class_Hierarchy classHierarchy;
public:
static void Register_Inheritence(const Type *derived, const Type *base);
template<typename Dst, typename Src>
static Dst new_static_cast(Src src);
template<typename Dst, typename Src>
static Dst new_dynamic_cast(Src src);
};
#include "a.cpp"
#endif /* A_H_ */
在 a.cpp 文件中:
#ifndef A_CPP_
#define A_CPP_
#include "hw5.h"
#include <type_traits>
#include <typeinfo>
inline void CASTS::Register_Inheritence(const Type *derived, const Type *base) {
std::map<const Type*, std::set<const Type*> >::iterator it;
it = CASTS::classHierarchy.map.find(derived);
}
#endif /* A_CPP_ */
我有另一个名为test.cpp
which的文件#includes a.h
并使用它的代码。
起初我在 CASTS 中有一个map
静态私有数据成员,并在.a.cpp
a.cpp
a.h
然后我遇到了另一个问题,我无法在 cpp 文件中初始化 map(CASTS 类的私有静态数据成员),因为我开始获取multiple definition error
. 因此,我尝试将Class_Hierarchy
其映射为公共数据成员,并Class_Hierarchy
在CASTS
类中创建一个静态实例以使用其映射,但我得到了undefined reference to CASTS::classHierarchy
.
我想不出这两个问题的解决方案,如何将模板类保留在头文件中并在 CASTS 类中有一个静态成员?
现在我唯一的错误是undefined reference to
CASTS::classHierarchy'`。
编辑:
我对每个成员函数都有多重定义错误,所以我在a.cpp
文件中添加了#include 保护。