gpt4 book ai didi

c++ - 这是构造函数运算符还是转换运算符?

转载 作者:IT老高 更新时间:2023-10-28 22:59:41 27 4
gpt4 key购买 nike

class B
{
public:
operator B() const{ } // What is this and what is the purpose?

private:
int m_i;
};

那么问题来了,那是转换运算符还是构造运算符,它有什么用呢?在哪里使用?

最佳答案

这是一个永远不会被隐式调用的转换函数。该标准实际上对此进行了深入探讨。 12.3.2/1:

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.

在脚注中,

These conversions are considered as standard conversions for the purposes of overload resolution (13.3.3.1, 13.3.3.1.4) and therefore initialization (8.5) and explicit casts (5.2.9). A conversion to void does not invoke any conversion function (5.2.9). Even though never directly called to perform a conversion, such conversion functions can be declared and can potentially be reached through a call to a virtual conversion function in a base class.

此外,转换函数仍然是普通函数,可以通过名称显式调用。

关于虚函数的注释适用于这样的代码:

class B;

struct A {
virtual operator B() const = 0;
};

struct B : A
{
public:
operator B() const{ return B(); } // virtual override

private:
int m_i;
};

A const & q = B(); // q has dynamic type B, static type A
B r = q; // Convert A to B using B::operator B()

迂腐提示:“转换运算符”是一个糟糕的术语。这些被称为 转换函数,尽管有 operator 关键字,但它们不被视为运算符重载的情况。

关于c++ - 这是构造函数运算符还是转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24161253/

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