在什么情况下,将调用类型自身的转换运算符? [英] Under what circumstances would a type's conversion operator to itself be invoked?

查看:80
本文介绍了在什么情况下,将调用类型自身的转换运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑类型bar,该类型具有用户定义的转换操作符来引用类型bar的引用:

Consider a type bar which has user-defined conversion operators to references of type bar:

struct bar
{
  operator bar & ();
  operator const bar & () const;
};

何时将应用这些转换?而且,这意味着这些运算符是否为deleted?两种功能都有有趣的用途吗?

When would these conversions be applied? Moreover, what does it imply if these operators were deleted? Is there any interesting use of either feature?

以下程序似乎均未应用任何转换:

The following program does not appear to apply either conversion:

#include <iostream>

struct bar
{
  operator bar & ()
  {
    std::cout << "operator bar &()" << std::endl;
    return *this;
  }

  operator const bar & () const
  {
    std::cout << "operator const bar &() const" << std::endl;
    return *this;
  }
};

void foo(bar x)
{
}

int main()
{
  bar x;

  bar y = x;         // copy, no conversion

  y = x;             // assignment, no conversion

  foo(x);            // copy, no conversion

  y = (bar&)x;       // no output

  y = (const bar&)x; // no output

  return 0;
}

推荐答案

C ++ 11§12.3.2

C++11 §12.3.2

从不使用转换函数将(可能具有cv限定)对象转换为(可能具有cv限定)相同的对象类型(或对其的引用),转换为该对象的(可能具有cv限定)的基类.类型(或对其的引用),或(可能具有cv资格)作废

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), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void

这篇关于在什么情况下,将调用类型自身的转换运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆