gpt4 book ai didi

c++ - 在什么情况下会调用类型自身的转换运算符?

转载 作者:可可西里 更新时间:2023-11-01 15:12:57 25 4
gpt4 key购买 nike

考虑一个 bar 类型,它具有用户定义的转换运算符到 bar 类型的引用:

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

何时应用这些转换?此外,如果这些运算符被删除,这意味着什么?这两个功能有什么有趣的用途吗?

以下程序似乎没有应用任何一种转换:

#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

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

关于c++ - 在什么情况下会调用类型自身的转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8350678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com