【问题标题】:C++ Template Class Compilation Error: expected init-declarator before '<' tokenC++ 模板类编译错误:“<”标记之前的预期 init-declarator
【发布时间】:2013-06-13 10:54:50
【问题描述】:

我正在学习 c++ 中的模板,并根据本教程:http://www.cprogramming.com/tutorial/templates.html

我创建了 CalcTempl.h 类

#ifndef CALC_TEMPL_H
#define CALC_TEMPL_H

template <class A_Type> class CalcTempl
{
  public:
    A_Type multiply(A_Type x, A_Type y);
    A_Type add(A_Type x, A_Type y);
};

template <class A_Type> A_Type calc<A_Type>::multiply(A_Type x,A_Type y)
{
  return x*y;
}
template <class A_Type> A_Type calc<A_Type>::add(A_Type x, A_Type y)
{
  return x+y;
}

#endif

和 main.cpp

#include <iostream>
#include "CalcTempl.h"

using namespace std;

int main(){

  CalcTempl<double> c2;

  double d1 = 5;
  double d2 = 4;

  double c2r1 = c2.add(d1, d2);

  cout << " C2 Result: " << c2r1 << "\n";

  return 0;
}

在编译时(g++ main.cpp -o ttest)我得到了这个错误:

CalcTempl.h:11: error: expected init-declarator before '<' token
CalcTempl.h:11: error: expected `;' before '<' token
CalcTempl.h:15: error: expected init-declarator before '<' token
CalcTempl.h:15: error: expected `;' before '<' token

我找不到问题所在

【问题讨论】:

    标签: c++ templates compiler-errors


    【解决方案1】:

    您的类称为CalcTempl,但在您实现其成员时,您尝试将其称为calc。那是行不通的。

    【讨论】:

    • 谢谢,多么愚蠢的错误!我认为编译器的输出让我走错了路。
    • 是的,模板错误可能会造成混淆。尝试使用 Clang 而不是 GCC,它通常有更好的错误消息。或者将您的 GCC 升级到 4.8,这也有很大的改进。顺便说一句,如果某个答案解决了您的问题,请点击投票下方的勾号将其标记为已接受。
    • @SebastianRedl 你能解释一下 init-declarator 是什么意思吗?
    • @VINOTHENERGETIC 这是 C++ 标准语法中的一个术语,大致意思是“在初始类型和修饰符之后的声明部分,包括初始化器(如果存在)”。
    • @VINOTHENERGETIC 这是一个基于语法编写方式的人为构造。实际类型,任何 const、volatile、static 等,它们都是 decl-specifier-seq。完整的声明由一个 decl-specifier-seq 和一个 init-declarator 组成。对于一个普通的 C++ 程序员(即没有实现编译器的人)来说,如果不是因为包含这些术语的考虑不周的错误消息,甚至不需要知道这些东西的存在。
    猜你喜欢
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多