Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为某些对象找到良好的建模方法_C++_Design Patterns_Types - Fatal编程技术网

C++ 为某些对象找到良好的建模方法

C++ 为某些对象找到良好的建模方法,c++,design-patterns,types,C++,Design Patterns,Types,对于学校项目,我需要通过网络发送和接收一些名为TLV的数据 事实上,因为TLV可能很小,所以应用程序会发送一个元TLV,将多个TLV分组到一个数据包中 我的问题如下:我需要创建哪些类来正确建模TLV 我不知道是否需要提及所有可能的TLV,但我知道的是: -每个TLV都有一个字段类型,用于标识TLV的语义 -除一个外,每个TLV都有一个字段长度。但是,对于五个TLV,该尺寸是固定的 -两个TLV具有完全相同的字段:类型,长度=0 -三个TLV具有完全相同的字段:type、length=8和id。只

对于学校项目,我需要通过网络发送和接收一些名为TLV的数据

事实上,因为TLV可能很小,所以应用程序会发送一个元TLV,将多个TLV分组到一个数据包中

我的问题如下:我需要创建哪些类来正确建模TLV

我不知道是否需要提及所有可能的TLV,但我知道的是:

-每个TLV都有一个字段类型,用于标识TLV的语义 -除一个外,每个TLV都有一个字段长度。但是,对于五个TLV,该尺寸是固定的 -两个TLV具有完全相同的字段:类型,长度=0 -三个TLV具有完全相同的字段:type、length=8和id。只有类型更改(及其名称)

另一种则完全不同

我的第一个想法是使用具有枚举的母类TLV来存储所有允许的不同TLV,如下所示:

//枚举类以避免冲突

enum class TlvType {
        Pad1,
        PadN,
        Bad,
        No,
        PeersReq,
        Peers,
        Data,
        IHave,
        IDontHave,
        INeed,
//      Unknown,
    };
class Tlv {
private:
    virtual void to_stream(std::ostream& output) const = 0;
protected:
    uint8_t length_;
public:

    virtual TlvType type() const = 0;

    /*Solution find here : http://stackoverflow.com/questions/2059058/c-abstract-class-operator-overloading-and-interface-enforcement-question*/
    friend std::ostream &operator<<(std::ostream& output, const Tlv& tlv) {
        tlv.to_stream(output);
        return output;
    }

    //TO DO : do we really need that this method is virtual ?
    virtual uint8_t length() const;

    Tlv();

    virtual ~Tlv() {}

};

class PadN : public Tlv {
private:
    void to_stream(std::ostream& output) const;
    static constexpr TlvType code() {return TlvType::PadN;}
public:
    TlvType type() const;
    PadN();
    PadN(uint8_t zero_bytes);
    void set_length(uint8_t length);
};
enum类TlvType{
Pad1,
帕丁,
不好,,
不
皮尔斯雷克,
同龄人,
数据,
我已经,
伊登塔夫,
伊内德,
//不详,
};
类Tlv{
私人:
虚拟空到_流(std::ostream&output)常数=0;
受保护的:
uint8_t长度;
公众:
虚拟TlvType type()常量=0;
/*解决方案可在此处找到:http://stackoverflow.com/questions/2059058/c-abstract-class-operator-overloading-and-interface-enforcement-question*/

friend std::ostream&operatorI建议您研究GoF的书籍设计模式。