假设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;
}