Pel*_*a86 4 c++ private class vector public
在 C++ 中,将类的数据保留为私有成员总是更好。
如果一个类有一个向量作为成员,最好把它作为私有成员还是公共成员?
如果我有一个向量作为私有成员,我将无法轻松访问该向量的成员函数。所以我必须为我需要访问向量方法的每个函数设计一个带有方法的类?
给出的例子:
class MyClass{
private:
std::vector<int> _myints;
public:
get_SizeMyints(){return _myints.size();}
add_IntToMyints(int x){_myints.push_back(x));
};
Run Code Online (Sandbox Code Playgroud)
还是最好保持向量公开并调用 MyClass._myints.push_back(x)?
- - - - - - - - - - -编辑 - - - - - - -
只是为了清楚这个问题需要什么:
蛇.h:
enum directions{UP, DOWN, RIGHT, LEFT, IN, OUT, FW, RW };
class Snake
{
private:
enum directions head_dir;
int cubes_taken;
float score;
struct_color snake_color;
V4 head_pos;
public:
std::vector<Polygon4> p_list; //the public vector which should be private...
Snake();
V4 get_head_pos();
Polygon4 create_cube(V4 point);
void initialize_snake();
void move(directions);
void set_head_dir(directions dir);
directions get_head_dir();
void sum_cubes_taken(int x);
int get_cube_taken();
void sum_score(float x);
float get_score();
void set_snake_color();
};
Run Code Online (Sandbox Code Playgroud)
所以现在我知道如何更改代码了。
顺便说一句......一个问题,如果我需要在这样的其他类中复制向量: GlBox.p_list = Snake.p_list (如果是私有的则有效)如果它们是私有的,什么是有效的方法?
运行 for 循环来复制元素并将它们推回 GLBox.p_list 对我来说似乎有点低效(但可能只是一种印象):(
如果有人出现并清空向量或重新排列它的所有元素并不重要,那么将其公开。如果这很重要,那么是的,您应该将其设置为受保护/私有,并像您一样制作公共包装器。[编辑] 既然你说“它是一条蛇”,那意味着如果有人来取走或更换位子,那就不好了。因此,您应该将其设为受保护或私有。[/编辑]
您可以简化其中的很多:
MyClass {
private:
std::vector<int> _myints;
public:
const std::vector<int>& get_ints() const {return _myints;}
add_IntToMyints(int x){_myints.push_back(x));
};
Run Code Online (Sandbox Code Playgroud)
该get_ints()功能将允许某人随意查看向量,但不会让他们更改任何内容。但是,更好的做法是完全封装向量。这将允许您稍后用双端队列或列表或其他内容替换向量。你可以得到大小std::distance(myobj.ints_begin(), myobj.ints_end());
MyClass {
private:
std::vector<int> _myints;
public:
typedef std::vector<int>::const_iterator const_iterator;
const_iterator ints_begin() const {return _myints.begin();}
const_iterator ints_end() const {return _myints.end();}
add_IntToMyints(int x){_myints.push_back(x));
};
Run Code Online (Sandbox Code Playgroud)