如何在课堂外返回枚举的向量?

pok*_*che 4 c++ enums vector

让我们说A类有2d enum向量,我想在类之外访问这个2d向量并操纵该值.

我的问题是:如何声明新向量以保持类在类之外的返回值,因为我的类型(枚举类型)在类中?我希望有点像

A a(5);
std::vector<std::vector<A::s> > x = a.get_2dvec();
Run Code Online (Sandbox Code Playgroud)

但这给了我错误说它的私有然后如果我使类型公开我没有声明错误.

我知道我可以放置枚举{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;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

get_2dvec()是一个成员函数,需要一个对象来调用它.如果您不想制作A::s public,可以使用auto说明符(因为C++ 11)来避免直接访问私有名称.(但我不确定这是否是你想要的.)

更改

std::vector<std::vector<enum-type> > x = get_2dvec();
Run Code Online (Sandbox Code Playgroud)

auto x = a.get_2dvec();
Run Code Online (Sandbox Code Playgroud)

  • @pokche使用`auto`的效果是有限的,还有一些情况无法解决.如果它适合您的设计,那么没问题.如果没有,你可以再考虑制作`A :: s`或`A :: color``public`. (2认同)