将向量声明为类成员
declaring a vector as a class member
我在头文件中有一个简单的类: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;
}
>
到目前为止一切都很好。我编译了代码,它编译得很好。但只要我在类中添加一个向量:
#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.
将这里的向量声明为成员有什么问题?
您需要#include <vector>
并使用限定名称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::
- 读一读"为什么";使用命名空间std";被认为是不好的做法
将向量声明为类成员:
#include <iostream>
#include <vector>
using namespace std;
class class_object
{
public:
class_object() : vector_class_member() {};
void class_object::add_element(int a)
{
vector_class_member.push_back(a);
}
void class_object::get_element()
{
for(int x=0; x<vector_class_member.size(); x++)
{
cout<<vector_class_member[x]<<" n";
};
cout<<" n";
}
private:
vector<int> vector_class_member;
vector<int>::iterator Iter;
};
int main()
{
class_object class_object_instance;
class_object_instance.add_element(3);
class_object_instance.add_element(6);
class_object_instance.add_element(9);
class_object_instance.get_element();
return 0;
}
1.您需要#include <vector>
和using namespace std
,然后a.hh,如下所示:
#ifndef a_hh
#define a_hh
#include <vector>
using namespace std;
class a
{
public:
int i;
vector <int> x;
a()
{
i = 0;
}
};
#endif
2.如果你不想在所有代码中只使用std名称空间,你可以在键入之前指定名称空间,就像std::vector<int> x;
相关文章:
- 使用静态成员声明类时遇到问题
- 错误 C2059:语法错误:从结构成员声明'constant'
- std::d eclare_if 或其他在编译时丢弃成员声明的假设方法
- C++ 成员声明中不允许使用限定名称
- 又一个"未找到成员声明"
- auto f = bind(dist<>,gen) 在成员声明C++失败。未被识别为函数
- C++错误:成员声明末尾的预期“;”
- 静态成员声明 c++11
- 如何将成员声明为指向外部"C"函数的指针?
- C++11 - 将非静态数据成员声明为 'auto'
- 类成员声明的快捷方式
- libclang 获取成员声明
- 将成员声明与enable_if一起使用
- 找不到成员声明
- C++错误:找不到成员声明
- 找不到c++成员声明
- 成员声明顺序在类中如果彼此依赖,则为最优解
- 将struct的成员声明为uint32_t时额外的字节
- 为什么类的大小取决于成员声明的顺序?以及如何
- 是成员声明`decltype(name)name;`在第一个名称引用封闭作用域的本地结构中允许