为什么我的代码抛出"没有命名类型错误"?

时间:2014-05-08 00:41:52

标签: c++

driver.cc

#include <iostream>

#include "dynStack.h"

using namespace std;

// class definition
int main()
{
  dynstack<double> it;
  cout << "hello";
  return 0;
}

dynStack.h

template <class T>
class dynstack {
public:
  dynstack();
  void push(T data);
private:


};

#include "dynStack.cc"

dynStack.cc

template <class T>
dynstack<T>::dynstack() { // <-- Here

}

template <class T> //  // <-- And here
void dynstack<T>::push(T data)
{
}

我是C ++的新手。粗体线是报告的错误。第一个说&#34;错误:&#39; dynStack&#39;没有命名类型&#34;第二个说&#34; exrror:预期的初始化程序&#39;&lt;&#39;令牌&#34 ;.我花了好几个小时才找到错误。有人可以帮忙吗?谢谢。

我得到了一个类似于此的示例解决方案。以下是样本:

main.cc

#include <iostream>
// #include the header file - as always
#include "temp.h"

using namespace std;

int main()
{
  Thing<int> it(1);

  Thing<double> dt(3.14);

  cout << endl;
  cout << "it = " << it.getData() << endl;
  cout << endl;
  cout << "dt = " << dt.getData() << endl;
  cout << endl;

  return 0;
}

temp.h

template <class T>
class Thing
{
  private:
    T data;
    void setData(T data);

  public:
    Thing(T data);
    T getData() const;
};

// MUST #include the implementation file here
#include "temp.cc"

temp.cc

// DO NOT #include the header file

template <class T>
Thing<T>::Thing(T data)
{
  this->setData(data);
}

template <class T>
void Thing<T>::setData(T data)
{
  this->data = data;
}

template <class T>
T Thing<T>::getData() const
{
  return this->data;
}

2 个答案:

答案 0 :(得分:3)

您似乎正在尝试编译driver.ccdynStack.cc。使用此设置编译的唯一文件是driver.cc

答案 1 :(得分:1)

试试这个:将dynstack.cc的内容完全移至dynstack.h并删除dynstack.cc

阅读评论回复后编辑:

如果你想保留dynstack.cc,那就好了,只要确保你没有尝试编译dynstack.cc我会把它命名为.cc以外的其他扩展名,这通常用于C ++实现。避免使用.cc.cpp.cxx等;使用不常见的扩展名,例如.hc: - )