我是 C++ 的新手,想为我的 vector 实现封装。
#pragma once
#include <vector>
using namespace std;
class Cell {
public:
Cell();
Cell(const Cell& cell);
void setVector(vector<int> vector[]);
vector<int> getVector(void)const;
private:
vector<int> m_vector;
};
我最近阅读了有关 STL 迭代器的内容,所以我想知道以这种方式实现我的 setVector()
方法是否是一种好的做法?如果是,您能否举例说明如何实现?
最佳答案
与其公开整个 vector ,无论是通过引用还是使用迭代器,您应该只公开您实际需要的 std::vector
的那些成员函数。
或者更准确地说:您应该只公开您实际需要的 std::vector
的功能。
查看所有 members provided by std::vector
: 你真的需要 Cell
来公开,比如说,allocator_type
、back
、pop_back
、operator> =
或 shrink_to_fit
?
实现实际封装而不仅仅是表面伪封装的更健壮的解决方案是从Cell
成员函数显式委托(delegate)给所需的 vector 成员函数。例如,如果您只需要大小和单个元素访问,那么为什么不向 Cell
添加一个 size
成员函数和一个 elementAt
成员函数并将这些功能的实现委托(delegate)给私有(private) vector ?
例子:
#include <vector>
class Cell {
public:
Cell(std::vector<int> const& vector) : m_vector(vector) {}
int size() const
{
return static_cast<int>(m_vector.size());
}
int elementAt(int index) const
{
return m_vector[index];
}
private:
std::vector<int> m_vector;
};
也许您甚至不需要构造函数中的 std::vector
参数。您可以采用任何您想要的输入并用它初始化私有(private) vector 。
顺便说一句,很可能由 C++17 建立的最佳实践也需要或至少鼓励您添加非成员函数 size
和 empty
到类中,以实现与std::empty
的兼容性和 std::size
功能:
bool empty(Cell const& cell)
{
return cell.size() == 0;
}
int size(Cell const& cell)
{
return cell.size();
}
关于c++ - 使用 STL 迭代器封装 vector 是一种好习惯吗?如果是?怎么做到的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43415718/