【发布时间】:2016-12-14 06:27:06
【问题描述】:
我对使用模板类继承的项目有疑问。 这个想法是让代理具有指向 msgtype 的指针。 msgtypes 可以不同,这就是模板类进入游戏的原因。 这个想法是通过接口类存储不同的消息类型。 要使用 msgtype 的实例初始化 Agent 中的接口指针,我需要 包括#include“msginterface.h”和#include“msgtype.h”。 不幸的是,如果我只包含“msginterface.h”,项目编译得很好。 但是,如果我在初始化所需的 Agent.h 中添加 #include "msgtype.h"。我收到了这个疯狂的错误:
我得到的错误是:
错误:预期的模板名称之前 ‘
你知道这个错误的原因是什么吗?
可以使用以下代码重现该错误:
//main.cpp
#include <stdio.h>
#include <iostream>
#include <agent.h>
using namespace std;
int main(void){
cout<<"Hello world"<<endl;
}
//agent.h
#ifndef _AGENT
#define _AGENT
#include "msginterface.h"
#include "msgtype.h"
class Agent{
MsgInterface* msg;
};
#endif
//msginterface.h
#ifndef _MSGINTERFACE
#define _MSGINTERFACE
#include <stdio.h>
#include <agent.h>
using namespace std;
class Agent; //Forward Declaration
class MsgInterface{
Agent* agent;
};
#endif
//msg.h
#ifndef _MSG
#define _MSG
#include <stdio.h>
#include <agent.h>
#include "msginterface.h"
using namespace std;
template <class T>
class Msg:public MsgInterface<T>{
};
#endif
//msgtype.h
#ifndef _MSGTYPE
#define _MSGTYPE
#include <stdio.h>
#include "agent.h"
#include "msg.h"
using namespace std;
template <class S>
class MsgTape:public Msg<S>{
};
#endif
【问题讨论】:
-
MsgInterface类不是模板类,你为什么要这样使用它? -
与您的问题无关,但以下划线开头的符号(甚至是预处理器符号,例如您的
_AGENT标头保护宏)后跟另一个下划线或大写字母被“保留”在所有范围内实现”(编译器和标准库)。有关更多信息,请参阅this question and its answers。
标签: c++ class templates inheritance template-classes