【问题标题】:using vector in c++ class definition在 C++ 类定义中使用向量
【发布时间】:2013-09-11 14:49:05
【问题描述】:

我有一个神秘的问题。尝试在旅游类中定义变量时,我不断收到 ‘vector' does not name a type 错误。该库似乎安装正确,因为我可以在 main.xml 中定义向量。根据这里的许多帖子,我检查了正确的向量包含和 std 命名空间。我仍然得到错误。

main.cpp

#include <vector>
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <cmath>
#include <cstdlib>
#include "tour.h"
using namespace std;

int main () {

        //vector declaration works here
return 0;
}

tour.h

#ifndef TOUR_H_
#define TOUR_H_

#include<vector>
using namespace std;

class tour
{
    public:
      //variables
      int teamID;
      vector<int> tourseq; //this is where the error occurs

      //functions
      tour(int);

};

#endif /* TOUR_H_ */

tour.cpp

#include<vector>
#include "tour.h"
using namespace std;

tour::tour(int id){
teamID = id;
}

这里有什么问题?

【问题讨论】:

  • 看起来不像真正的代码。不过有一个提示:停止使用using namespace。拒绝吧。我敢打赌,你的问题会在这个过程中消失。
  • 使用构造函数初始化列表。
  • 你是什么意思没有真正的代码,我把它剥离到最小的相关部分,因为我认为这是这个网站上的最佳实践?不管怎样,我一开始并没有使用命名空间std,根据我看到的一个帖子添加它。删除它并不能解决问题。
  • @dorien:你确定这段代码会产生错误吗?它不适合我:ideone.com/wuLdnE
  • @dorien 这不是 真正的代码 (coliru.stacked-crooked.com/a/38d18f89a6c7cbfb)。这是“真正的”代码,好吧。真实包括,例如:)

标签: c++ vector


【解决方案1】:

考虑写std::vector&lt;int&gt; tourseq;,而不是写using namespace std;vector&lt;int&gt; tourseq;

可能无论如何都不应该将using namespace std; 放入您的代码中。

【讨论】:

  • 对不起,这是个好建议,但考虑到这个问题,它没有任何意义作为答案。
  • 我会完全删除“可能”,以提供更好的建议。
  • 是的,我什么都试过了。一开始我没有命名空间,但这样做是因为我在某处读过它。删除它没有效果。
  • 谢谢。我说“可能”是因为我认为在某些情况下它是有意义的(尽管我想不出除了肮脏的原型代码之外的任何情况——即使那样我也不会使用它)
  • @dorien,你能对编译单元进行预处理吗?你用的是什么编译器?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
相关资源
最近更新 更多