我尝试了以下层次结构但它没有链接。没有看到对c->Execute()
的调用,因为它似乎被Execute
中的Derived
屏蔽,并且它找不到足够的类型来使用。我原本以为如果出现问题,就必须在汇编时显示。我已尝试使用GCC 4.8在线和在Windows上使用borland编译器。两种情况下的错误消息都类似。按顺序排列:
/tmp/ccrT5mNy.o:(.rodata._ZTV7DerivedI5TypeCE[_ZTV7DerivedI5TypeCE]+0x10): undefined reference to `Derived<TypeC>::Execute()'
collect2: error: ld returned 1 exit status
我会非常感谢任何指示。
#include <iostream>
class BaseType
{
public:
BaseType() {}
virtual void Execute() { std::cout << "BaseType execute..." << std::endl; };
protected:
};
struct TypeA;
struct TypeB;
struct TypeC;
class Derived2 : public BaseType
{
public:
Derived2() : BaseType() {}
virtual void Execute() { std::cout << "Derived execute2" << std::endl; }
protected:
};
template <typename T>
class Derived : public BaseType
{
public:
Derived() : BaseType() {}
virtual void Execute();
protected:
};
template <typename T>
class GrandChild : public Derived<T>
{
public:
GrandChild() : Derived<T>() {}
void Execute();
};
template<>
void Derived<TypeA>::Execute() { std::cout << "Derived execute... TypeA" << std::endl; }
template<>
void Derived<TypeB>::Execute() { std::cout << "Derived execute... TypeB" << std::endl; }
template<>
void GrandChild<TypeC>::Execute() { std::cout << "Derived execute... TypeC" << std::endl; }
int main()
{
BaseType* a = new Derived<TypeA>();
BaseType* b = new Derived<TypeB>();
BaseType* c = new GrandChild<TypeC>();
BaseType* d2 = new Derived2();
a->Execute();
b->Execute();
c->Execute();
d2->Execute();
delete a;
delete b;
delete c;
delete d2;
}
答案 0 :(得分:1)
Derived<TypeC>::Execute()
,因为您正在实例化类模板。尝试添加一个空的定义,或throw
s等的定义,程序应链接并按预期工作。