c++ - 重载引用转换

标签 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; }
};

指定转换为自身引用的函数是否会被简单地忽略?

最佳答案

引用自 12.3.2

转换函数永远不会用于将(可能是 cv 限定的)对象转换为(可能是 cv 限定的)相同对象类型(或对它的引用)

此外,在 gcc 上使用 -Wall -Wextra -pedantic -ansi 给我:warning: this statement has no effect for the static cast。 (另外,尝试 clang online 它会给你一些不错的编译器错误消息)。

关于c++ - 重载引用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628894/

相关文章:

string - Matlab:将数字数组转换为字符串数组

编译器独立的表达式算术转换和整数提升

c++ - 如何配置 CppCheck 以阻止函数的使用

c++ - 将基类动态转换为派生对象

c# - AutoMapper,如何保持映射对象之间的引用?

c++ - 将值传递给 const 引用参数?

c# - 这种将字符串强制为整数或默认为 0 的扩展方法是否多余?

c++ - 使用 winsock 发送 POST 数据(并使用 PHP 服务器端脚本接收它们)

c++ - Xcode C++ : Build in Debug but not Release

c++ - 更好地理解 C++ 中的 Singleton 类