提问者:小点点

C++意外隐含转换


#include <cstddef>

struct foo
{
    int operator[](size_t i) const { return 1; }
    operator char() const { return 'a'; }
};

int main()
{
    foo f;
    f["hello"]; // compilation error desired here
}

从中提取代码的类确实需要隐式转换和运算符[]。那么,有没有一种方法可以在不明确转换的情况下防止这种行为呢?


共1个答案

匿名用户

行编译的原因是,通过隐式转换,它可以被重新解释为'a'[“hello”];,这又与编写*(('a')+(“hello”))相同;也进行编译。

标准摘录:

5.2.1订阅:

struct foo
{
  operator char() const { return 'a'; }
  int operator[](size_t i) const { return 1; }

  // prevent accidental use of foo["hello"]
  int operator[](char const*) const = delete;
};

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|意外|隐含|转换)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?