【问题标题】:How to make well-encapsulated classes while using unordered_set/map in c++?在 c++ 中使用 unordered_set/map 时如何制作封装良好的类?
【发布时间】:2021-07-05 17:18:37
【问题描述】:

我正在查看一些关于如何为类/结构制作 unordered_set 的教程。我发现这个易于理解的代码(作为 Java 开发人员)可以解决问题:

#include <iostream>
#include <unordered_set>
using namespace std;

struct Node{
    int val;
  
    bool operator==(const Node& n) const{
        return (this->val == n.val);
    }
};

class HashFunction{
    public:
        size_t operator()(const Node& n) const{
            return n.val;
        }
};

int main(){
    Node n1 = { 1 }, n2 = { 2 },
         n3 = { 3 }, n4 = { 4 };

    unordered_set<Node, HashFunction> us;
    us.insert(n1);
    us.insert(n2);
    us.insert(n3);
    us.insert(n4);
    
    for (auto node : us){
        cout << node.val << " ";
    }
    cout << endl;
    return 0;
}

我想知道我们是否可以将struct Node 设为类,将int val 设为私有字段并将unordered_set&lt;Node, HashFunction&gt; neighbours 作为字段添加到Node 类。

如果没有,保持类/结构良好封装并为类设置集合/映射字段的良好做法是什么?

【问题讨论】:

  • 请注意,C++ 中的 Node 表示实际对象,而不是 Java 中的指针。 “邻居”集合需要多对多关系,只能用指针来实现。
  • Struct 只是一个默认对所有成员公开的类。如果您将 val 设为私有,则类 Hash 无法返回它。
  • @BenVoigt 感谢您的评论,您的意思是“邻居”集应该有一个 Node* 作为模板吗?
  • @sucksatnetworking 感谢您的评论。我现在将尝试使“节点”成为一个类。

标签: c++ design-patterns encapsulation unordered-map unordered-set


【解决方案1】:

这里有几个问题,所以我会尝试按顺序回答:

可以使struct Node 成为一个类

是的,structclass 仅在它们的默认权限上有所不同(在 struct 中,除非另有说明,否则在 class 中它们是 private) 所以这和你写的代码是一样的:

class Node{
public:
    int val;
  
    bool operator==(const Node& n) const{
        return (this->val == n.val);
    }
};

int val 设为私有字段并将unordered_set&lt;Node, HashFunction&gt; neighbours 作为字段添加到Node

是的,你可以。我能想到的从您编写的代码进行转换的最简单方法是使HashFunction 成为Node 的子类。 例如:

class Node {
    class HashFunction {
        public:
            size_t operator()(const Node& n) const{
                return n.val;
            }
    };

public:
    Node(int _val) : val(_val) {}

    bool operator==(const Node& n) const{
        return (this->val == n.val);
    }

    // More methods here

private:
    int val;
    unordered_set<Node, HashFunction> neighbours;
};

如果没有,保持类/结构良好封装并为类设置集合/映射字段的良好做法是什么?

我想在这种情况下这是一个无声的问题 - 但一般的答案是只公开最低要求的接口。例如,现在HushFunction 知道Node 的内部内容。为了增加封装,我们可以向Node 添加一个hush 方法,并让HushFunction 调用该方法。这样,如果Node 的内容发生变化,Node 之外的任何内容都不需要注意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-14
    • 2014-05-05
    • 1970-01-01
    • 2012-11-21
    • 2017-10-14
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多