【问题标题】:The Boost library, serialization, and an ampersand operator?Boost 库、序列化和 & 运算符?
【发布时间】:2012-07-16 03:58:56
【问题描述】:

我来自 Java 和 C# 背景,作为深入研究 C++ 的一种方式,我正在使用 Qt 和 Boost 构建一个图标停靠。查看序列化的文档,我偶然发现了 & 运算符的一些有趣用法。

class gps_position
{
private:
    friend class boost::serialization::access;
    // When the class Archive corresponds to an output archive, the
    // & operator is defined similar to <<.  Likewise, when the class Archive
    // is a type of input archive the & operator is defined similar to >>.
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & degrees;
        ar & minutes;
        ar & seconds;
    }
    int degrees;
    int minutes;
    float seconds;

& 运算符的目的是非常清楚地读取 cmets。我想知道的是,它是如何实现的?它怎么知道“&”应该是什么意思?我在 Google 上搜索了 & 运算符的更多用途,但我能找到的只是 & 用于表示引用而不是操作。

谢谢。

【问题讨论】:

  • 重载的按位与运算符(意​​味着完全不同的东西)。
  • 在我看来,这就是为什么覆盖位运算符通常是个坏主意的一个例子。
  • 对于&amp; 的这种使用,没有什么比其他任何名称不佳的方法都更加模棱两可了。

标签: c++ boost operator-overloading boost-serialization


【解决方案1】:

按位与重载的示例:

class Archive {
public:
   std::ostream& operator&( std::ostream& out ) {
       return out << to_string();
   }
   std::string to_string() { return "a string"; }
};

【讨论】:

    【解决方案2】:

    对于非内置类型,您可以在 C++ 中定义运算符行为。

    详情请见C++ FAQ

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 2011-12-28
      • 2015-03-19
      • 1970-01-01
      相关资源
      最近更新 更多