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

时间:2016-08-15 06:12:28

标签: c++ vector enums

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

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

这样的东西
A a(5);
std::vector<std::vector<A::s> > x = a.get_2dvec();

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

我知道我可以放置枚举{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;
}

2 个答案:

答案 0 :(得分:5)

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

更改

std::vector<std::vector<enum-type> > x = get_2dvec();

auto x = a.get_2dvec();

答案 1 :(得分:2)

你的枚举属于班级的私人部分。

默认情况下,默认情况下会class启用private,而struct默认启动public

将其移至公共部分

另外,通过引用返回值,在常量getter方法或性能和接口质量一般会受到影响。

我也会自己输入矩阵,并在课堂上一次性使用它,从而导致我把私有部分放在最后。

编辑:因为回答问题也意味着从别人那里学习东西,我完全重构了const引用的示例,auto,所有类型私有,所有工作,只是为了记录(并且它构建)。

#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;
}