简体   繁体   English

C++ 多重转换运算符

[英]C++ multiple conversion operators

I defined a class as below with two member variables and two conversion operators (operator float and operator chrono::microseconds).我用两个成员变量和两个转换运算符(运算符 float 和运算符 chrono::microseconds)定义了一个类,如下所示。 But the code below only works if I comment out the float operator.但是下面的代码只有在我注释掉浮点运算符时才有效。 Otherwise, it throws an error (cannot convert type).否则,它会抛出错误(无法转换类型)。 I can't figure out why?我想不通为什么?

#include <iostream>
#include <chrono>

using namespace std::chrono_literals;

class Peak {
public:
  Peak (std::chrono::microseconds t, float magnitude)
  : t_(t),
    magnitude_(magnitude)
  {
  };

  std::chrono::microseconds get_t() { return t_; }
  //have to comment this out or I get an error
  operator float() { return magnitude_; }
  operator std::chrono::microseconds() {
      return t_;
  }
private:
  std::chrono::microseconds t_{2us};
  float magnitude_;
};

int main()
{
  Peak a{3us, 100};
  std::cout
    << "t is "
    << static_cast<std::chrono::microseconds>(a).count();
}

Looks like a compiler bug in GCC 7.3 and older.看起来像是 GCC 7.3 及更早版本中的编译器错误。 A workaround seems to be building using the -std=c++17 flag.解决方法似乎正在使用-std=c++17标志构建。 Alternatively, making the float conversion operator explicit also fixes it:或者,使float转换运算符explicit也可以修复它:

explicit operator float() const { return magnitude_; }

(It's always a good idea to mark these const , by the way.) (顺便说一下,标记这些const总是一个好主意。)

Update:更新:

Actually, just making these operators const seems to fix it already without the need to make the float one explicit nor to build with -std=c++17 .实际上,只需让这些运算符const似乎已经修复它,而无需使float explicit也无需使用-std=c++17构建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM