c++ - 使用 STL 迭代器封装 vector 是一种好习惯吗?如果是?怎么做到的?

标签 c++ stl encapsulation

我是 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_typebackpop_backoperator> =shr​​ink_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 建立的最佳实践也需要或至少鼓励您添加非成员函数 sizeempty 到类中,以实现与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/

相关文章:

c# - 即使宣布公开也无法访问属性(property)

c++ - 这是访问类数据成员的正确方法吗?

c++ - 已签名/未签名函数的警告

c++ - 在 header 中声明和初始化 vector (还有其他 STL 容器)

c++ - 将单个参数传递给需要迭代器范围的函数

java - 该设计在多大程度上违反了封装性

java - 使用 Builder 也可以构建封装对象

c++ - 在 Qt 中释放和恢复嵌入窗口

c++ - 三次贝塞尔曲线上到给定点的最近点

c++ - 对象 vector