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

标签 c++

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/

相关文章:

c++ - 线程 sleep 导致内存泄漏

C++ - 从 main 之外的方法访问数组(在 main 中)

c++ - 为什么 clock::is_steady 返回 const bool 而不是 bool?

c++ - 如何使用迭代器在 vector 中导航? (C++)

c++ - 在 DLL 注入(inject)中访问内存会导致内存访问冲突

c++ - 运行 TrainCascade.exe 时出错

python - 从 C++ 调用 Python 或 Lua 来计算表达式,仅在需要时计算未知变量

c++ - 从表中提取用户数据,使用 lua c API

c++ - 如何在 std::map 类中定义迭代器

c++ - 变量类派生自某个抽象类的类模板