如何在类之外返回枚举向量
How to return vector of enum outside the class?
假设A类有一个枚举的2d向量,我想在类外访问这个2d向量并操作它的值。
我的问题是:我怎么能声明新的向量保持返回值外的类,因为我的类型(enum类型)是类内部?我希望看到一些类似
的东西A a(5);
std::vector<std::vector<A::s> > x = a.get_2dvec();
但是这给了我一个错误,说它是私有的然后如果我把类型设为公共类型,我就没有声明错误
我知道我可以放置enum s {RED, BLUE, GREEN};typepedef是color;在类之外实现结果,但是让我们假设main在不同的文件上。
// f1.cpp
#include <iostream>
#include <vector>
class A{
// This enum is inside class
enum s {RED, BLUE, GREEN};
typedef s color;
const int size = 3;
std::vector<std::vector<color> > color_array;
public:
A(int size_):size(size_),color_array(size){
std::cout << "vector size = " << color_array.size() << std::endl;
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
color_array[i].push_back(RED);
}
}
}
void print(){
for(auto it = color_array.begin(); it != color_array.end(); it++){
for(auto itt = it->begin(); itt != it->end(); itt++){
std::cout << *itt << " : " << std::endl;
}
}
}
// pass vector by value
std::vector<std::vector<color> > get_2dvec(){
return color_array;
}
};
// main.cpp
int main(){
A a(4);
a.print();
// here I some how need to capture the 2d enum vector
std::vector<std::vector<enum-type> > x = get_2dvec();
return 0;
}
get_2dvec()
是成员函数,需要一个对象来调用它。如果你不想让A::s
成为public
,你可以使用自动说明符(从c++ 11开始)来避免直接访问私有名。(但我不确定这是否是你想要的。)
std::vector<std::vector<enum-type> > x = get_2dvec();
auto x = a.get_2dvec();
枚举位于类的私有部分。
class
默认在private
中启动,struct
默认在public
中启动。
移动到公共部分
此外,通过引用返回值,在常量getter方法中或性能和接口质量一般会受到影响。
我也会对矩阵本身进行类型定义,并立即在类中使用它,从而导致我将私有部分放在最后。
编辑:因为回答问题也意味着从别人那里学习东西,我已经用const引用,auto,所有类型private,所有作品完全重构了这个例子,只是为了记录(和它构建)。
#include <vector>
#include <iostream>
class A
{
private:
// This enum is inside class
const int size = 3;
enum s {RED, BLUE, GREEN};
typedef s color;
typedef std::vector<std::vector<color> > ColorMatrix;
ColorMatrix color_array;
public:
A(int size_):size(size_),color_array(size){
std::cout << "vector size = " << color_array.size() << std::endl;
for(auto &it : color_array){
it.resize(size,RED);
}
}
void print() const{
for(const auto &it : color_array){
std::cout << " :";
for(const auto &itt : it){
std::cout << " " << itt;
}
std::cout << std::endl;
}
}
// pass vector by const reference to avoid copies
// (for better performance)
const ColorMatrix &get_2dvec() const {
return color_array;
}
};
// main.cpp
int main(){
A a(4);
a.print();
// here I some how need to capture the 2d enum vector
const auto &x = a.get_2dvec();
return 0;
}
相关文章:
- 枚举进程模块在有效句柄上返回无效句柄
- 使用枚举作为条件,if 条件将返回什么,真或假?
- 无法将返回的枚举与枚举进行比较
- 对clang、gcc和icc中开关枚举类返回的处理一致
- 如何为返回枚举元组的 C++ 函数编写 cython 包装器?
- 元编程构造,它返回枚举的基础类型和迭代器的整数
- 如何根据枚举参数返回其他类型
- 沿枚举 c++ 返回变量类型
- 使用枚举确定返回结果的类型(使用宏的黑客)
- 了解 Levenberg Marquardt 枚举返回
- 一种创建将字符串常量返回给枚举的类的廉价方法,反之亦然
- 如何定义在外部类之外返回枚举黑客的嵌入式类的方法?
- 地址数组,带有枚举的返回值
- 是否可以定义一个宏来定义枚举类和返回枚举元素计数的 GetCount() 方法
- 如何在此程序中显示返回枚举类型数据的函数
- 返回枚举,看不懂代码行
- 为什么可以将枚举作为函数变量传递,但不能返回枚举?
- c++静态结构模板方法返回枚举类型
- c++函数返回枚举
- 如何在类之外返回枚举向量