代码之家  ›  专栏  ›  技术社区  ›  f0b0s

C++ POD初始化

  •  1
  • f0b0s  · 技术社区  · 14 年前

    我已经阅读了C++中的POD对象。我想把pod结构写进一个文件。因此,它应该只有没有ctors/dtors等的公共数据,但据我所知,它可以在其中具有静态功能。那么,我可以在这里使用“命名构造函数习语”吗?我需要动态初始化,但我不想在每次结构初始化时检查重复的参数 下面是一个简单的例子 简单的 例如,不是工作代码):

    struct A
    {
      int day;
      int mouth;
      int year;
    
       static A MakeA(const int day, const int month, const int year)
       {  
          // some simple arguments chech
          if ( !(day >= 1 && day <= 31) || !(month >=1 && month <=12) || !(year <= 2010) )
             throw std::exception();
    
          A result;
          result.day = day;
          result.month = month;
          result.year = year;
          return result;
       }
    };
    

    所以我有某种构造函数和pod结构,我可以简单地写入一个文件?这是正确的吗?

    3 回复  |  直到 14 年前
        1
  •  4
  •   James Curran    14 年前

    那就好了。

    甚至可以拥有非静态成员函数(只要它们不是虚拟的)

    你不能有所谓的东西 自动地 (如ctor/dtor)。你直呼的东西没问题。

        2
  •  1
  •   Loki Astari    14 年前

    如果您编写流操作符,它将使生活简单得多。
    这并不是说用二进制格式写的速度要快得多(因为您需要编写代码来转换不同的endian格式),而现在的空间实际上是不相关的。

    struct A
    {
      int day;
      int mouth;
      int year;
    
       A(const int day, const int month, const int year)
       {  
          // some simple arguments chech
          if ( !(day >= 1 && day <= 31) || !(month >=1 && month <=12) || !(year <= 2010) )
             throw std::exception();
    
          this->day    = day;
          this->month  = month;
          this->year   = year;
       }
    };
    std::ostream& operator<<(std::ostream& str, A const& data)
    {
        return str << data.day << " " << data.month << " " << data.year << " ";
    }
    std::istream& operator>>(std::istream& str,A& data)
    {
        return str >> data.day >> data.month >> data.year;
    }
    

    有了这个定义,整个标准算法变得可用和易于使用。

    int main()
    {
        std::vector<A>    allDates;
        // Fill allDates with some dates.
    
        // copy dates from a file:
        std::ifstream  history("plop");
        std::copy(std::istream_iterator<A>(history),
                  std::istream_iterator<A>(),
                  std::back_inserter(allDates)
                 );
    
        // Now  save a set of dates to a file:
        std::ofstream  history("plop2");
        std::copy(allDates.begin(),
                  allDates.end(),
                  std::ostream_iterator<A>(history)
                 );
    }
    
        3
  •  1
  •   Omnifarious    14 年前

    你说得对。这只是一个普通的老数据。里面没有有趣的虚拟表指针或类似的东西。

    现在,我仍然不确定简单地使用 fwrite 将数据写入文件。你可以这样做 fread 返回的数据提供了执行 弗雷德 是用相同版本的编译器编写的 写入文件 首先。但是,如果您切换编译器、平台,或者有时甚至是版本,这可能会改变。

    我建议你吃点什么 Protocol Buffers 做使数据结构持久化的工作。

    推荐文章