当您知道结构将来会更改时,实现结构读写的最佳方法是什么

What is the best way to implement a read and write of a struct when you know the struct will change in the future?

本文关键字:结构 读写 实现 方法 最佳 是什么 将来      更新时间:2023-10-16

如果我有一个我知道尚未完全定义的struct A,但我知道"a"和"b"是它的成员,我需要编写一个函数来读取和填充它的 xml 并将其写入 xml 就像现在一样。

我如何编写读写方法,以便将来有人需要向struct A添加成员,我可以帮助他收到错误,说他们还需要实现支持额外成员功能的相应读写?

struct A
{
  string a, b;
}
void read(A&);
void write(A&);
// in the future
// A becomes 
struct A
{
 string a, b, c;
}
void read(A&); // should give a useful error saying the read is outdated
void write(A&); // should give a useful error saying the write is outdated

将版本号或格式编号写为第一项(可能是第二项(。

读取格式编号。

确定如何根据格式版本读取其余字段。

只做面向对象的编程,不要让数据成员从类外部访问。这样,每次更改数据成员时,您都知道可能必须重新实现所有成员函数。这就是对象编程的原因:将函数和它们操作的数据紧密地结合在一起。

class A{
private:
  string a,b,c;
public:
  void read();
  void write() const;
};
// free function helpers:
void read(A&a){ a.read();}
void wirte(const A& a){a.write();}

由于您主要要求模式,因此我将在结构中使用构造函数。这使您的代码库变得简单,任何阅读它的人都可以看到属于一起的部分。

struct A 
{
    string a, b, c;
    A(a1,b1,c1) : a(a1), b(b1), c(c1) : { }; 
}

当您通过字符串 d 扩展结构 A 时,您有 2 种方法:

  1. 扩展现有构造函数,
  2. 添加另一个构造函数并保留当前构造函数以实现兼容性

关于读取函数:如果你的结构有点私有(在一个类中(,你可以定义一个公共函数,返回你的结构1:1,或者你直接访问你的结构。您还可以在结构本身中定义成员函数(语法类似于类成员(

参考:http://en.cppreference.com/w/cpp/language/initializer_list