c++ - c 风格的类型转换和 operator()

标签 c++ gcc keil

问题已更改!

我使用一种简单的方法从本地 namespace 中隐藏我的枚举 - 结构内部的枚举。大致是这样的:

struct Color
{
    enum Type
    {
        Red, Green, Black
    };
    Type t_;
    Color(Type t) : t_(t) {}
    operator Type () const {return t_;}
private:
  template<typename T>
  operator T () const;
};

operator T() 是对隐式类型转换的保护。然后我尝试用 gcc 和 keil 编译这段代码:

Color n;
int a[9];
a[ (int)n ] = 1;

gcc 编译它没有错误(这是我所期望的),但是 Keil 给了我一个错误: “无效的类型转换。operator () 不可访问”。

所以我的问题是:哪个编译器是正确的?

我知道 c++11 枚举类,但现在 Keil 不支持它

最佳答案

Should reinterpret_cast (not c-style () cast) call type conversion operator?

不,reinterpret_cast 仅用于一些不可靠的转换类型:

  • 将指针转换为整数并返回
  • 在指向不相关类型的指针(和引用)之间进行转换

您根本不需要强制转换就可以使用隐式转换运算符——您根本没有阻止隐式转换。在 C++11 中,如果运算符是显式,那么您需要一个static_cast

如果您坚持使用 C++03,并且您真的想阻止隐式转换但允许显式转换,那么我认为唯一明智的做法是提供一个命名转换函数。

更新:问题现在变了,询问的是 C 风格的转换而不是 reinterpret_cast。这应该可以编译,因为任何可以通过 static_cast 完成的转换(包括隐式转换)也可以通过 C 风格的转换来完成。

关于c++ - c 风格的类型转换和 operator(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16671365/

相关文章:

c++ - 通过 Visual Studio 运行时无法打开文件

c - __builtin_add_overflow 函数在 gcc 5 及更高版本中受支持,在 gcc 4.6 中哪些函数可以替代它?

c - Keil Arm 编译器 : Is there a way to hook in the same function for two interrupts without modifying the Interrupt Vector Table?

c - 将外部静态库的段放置到特定位置

c++ - 使用带有指针/类的 set 方法

c++ - 从 C++ 到 C 文件中定义的变量/函数的 undefined reference

c++ - 构造一个通过类列表中的索引选择的类,c++

c - 什么时候应该使用 gcc 的 -m32 选项?

c - GCC 内存屏障 __sync_synchronize 与 asm volatile ("": : :"memory")

c++ - 无法在 keil c 项目中添加 C++ 库