c++ - 在类中存储固定的已知数据(c++)

标签 c++ class dictionary oop

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它.

1年前关闭。




Improve this question




我有这个类来存储固定的已知数据。每个对象都应该有自己的唯一 ID,这样,当用户调用 Belt belt(1) , 一个具有正确值的对象 name , perimeter , nOfPoints被 build 。有没有更好的方法来定义这些其他参数而不使用 switch-case?我应该以另一种方式设计吗?这种实现的缺点是什么?

class Belt {
    private:
        int _id;
        std::string _name;
        int _perimeter;
        int _nOfPoints;
    public:
        Belt(int id){
            _id = id;
            switch (id)
            {
            case 1:
                _name = "NEO";
                _perimeter = 100;
                _nOfPoints = 10;
                break;
            case 2:
                _name = "PED";
                _perimeter = 200;
                _nOfPoints = 12;
                break;
            case 3:
                _name = "ADT";
                _perimeter = 400;
                _nOfPoints = 20;
                break;
            }
        }
};

最佳答案

Is there any better way to define these other parameters without a switch-case?


您可以使用私有(private)静态 map 来保存您的原型(prototype):
class Belt {
private:
    static const std:map<int,Belt> prototypes;
    int _id;
    std::string _name;
    int _perimeter;
    int _nOfPoints;

    Belt(int id, const std::string name, int perimeter, int nOfPoints)
        : _id(id), _name(name), _perimeter(perimeter), _nOfPoints(nOfPoints) {}
public:
    Belt(int id) {   
        _id = id;
        _name = prototypes[_id]._name;  
        _perimeter= prototypes[_id]._perimeter;  
        _nOfPoints= prototypes[_id]._nOfPoints;  

        // Or simpler instead of the lines above:
        // *this = prototypes[id];
    }
};

const std:map<int,Belt> Belt::prototypes = {
      { 1 , Belt(1,"NEO",100,10) }
    , { 2 , Belt(2,"PED",200,12) }
    , { 3 , Belt(3,"ADT",400,20) }
};

此外,您可能有兴趣查看 Prototype Design Pattern .这是您可以使用的另一种技术,并为您提供更好的灵 active 。

关于c++ - 在类中存储固定的已知数据(c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64128444/

相关文章:

c++ - 针对 Automake 生成的库进行编译时 undefined reference

javascript - 调用类实例方法onclick javascript

class - 使用 Sed 和字符类从大写到小写

python - 数据的多处理加载并提交给 sqlalchemy

c++ - C++11 中 lambda 的内存管理

c++ - Visual C++ 中的 "No appropriate default constructor available"错误

c++ std vector 用现有对象初始化

java - 如何在 Java 中实现许多类通用的自定义方法?

Scala 在迭代时更新映射中的值

c# - 添加词典条目时出现异常