【问题标题】:Interfacing and Inheritage of template classes in c++c++中模板类的接口和继承
【发布时间】: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


【解决方案1】:

您没有将 MsgInterface 声明为模板化类。

尝试类似:

template<class Agent>
class MsgInterface 
{
  Agent* agent;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多