重载参考转换

时间:2012-03-09 04:21:23

标签: c++ reference type-conversion implicit-conversion

以下类似乎compile,但从不调用转换运算符:

class A
{
public:
  operator A() const { std::cout << "A() called" << std::endl; return *this; }
  operator A&() { std::cout << "A&() called" << std::endl; return *this; }
  operator const A&() const { std::cout << "const A&() called" << std::endl; return *this; }
};

是否指定转换为对自身的引用的函数只是被忽略了?

1 个答案:

答案 0 :(得分:1)

这里引用了12.3.2

A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it)

另外,在gcc上使用-Wall -Wextra -pedantic -ansi给了我:warning: this statement has no effect用于静态强制转换。 (另外,尝试clang online它会给你一些不错的编译器错误消息)。