将向量声明为类成员 [英] declaring a vector as a class member
本文介绍了将向量声明为类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在头文件中有一个简单的类:a.hh
I have simple class in a header file: a.hh
#ifndef a_hh
#define a_hh
class a
{
public:
int i;
a()
{
i = 0;
}
};
#endif
然后我有一个文件:b.cc
#include <iostream>
#include "a.hh"
using namespace std;
int main(int argc, char** argv)
{
a obj;
obj.i = 10;
cout << obj.i << endl;
return 0;
}
>
到目前为止一切都很好.我编译了代码,它编译得很好.但是一旦我在类中添加了一个向量:
Till this point everything is fine. I compile the code and it compiles fine. But as soon as i add a vector in the class:
#ifndef a_hh
#define a_hh
class a
{
public:
int i;
vector < int > x;
a()
{
i = 0;
}
};
#endif
我收到如下编译错误:
> CC b.cc
"a.hh", line 7: Error: A class template name was expected instead of vector.
1 Error(s) detected.
在此处将向量声明为成员有什么问题?
What is the problem with declaring a vector here as a member?
推荐答案
您需要#include
并使用限定名称 std::vector
:
You need to #include <vector>
and use the qualified name std::vector<int> x;
:
#ifndef a_hh
#define a_hh
#include <vector>
class a{
public:
int i;
std::vector<int> x;
a() // or using initializer list: a() : i(0) {}
{
i=0;
}
};
#endif
其他要点:
- (如 EitanT 所评论)我删除了构造函数上的附加限定
a::
- 阅读为什么是"使用命名空间标准"被认为是不好的做法?
这篇关于将向量声明为类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文