作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
假设一个类有枚举的二维 vector ,我想在类之外访问这个二维 vector 并操纵该值。
我的问题是:由于我的类型(枚举类型)在类内部,我如何声明新 vector 以在类外部保存按值返回?我希望像
A a(5);
std::vector<std::vector<A::s> > x = a.get_2dvec();
但这给我错误说它是私有(private)的,然后如果我将类型设为公开,我将得到未声明的错误。
我知道我可以放置 enum s {RED, BLUE, GREEN};和 typedef 的颜色;在类之外并取得结果,但可以说主要在不同的文件上。
// 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
,你可以使用 auto specifier (C++11 起)避免直接访问私有(private)名称。 (但我不确定这是否是您想要的。)
改变
std::vector<std::vector<enum-type> > x = get_2dvec();
到
auto x = a.get_2dvec();
关于c++ - 如何在类外返回枚举 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38950107/
我是一名优秀的程序员,十分优秀!