class B
{
public:
operator B() const{ } // What is this and what is the purpose?
private:
int m_i;
};
So the question is, is that a conversion operator or constructor operator and what is the use of it? Where to use it?
It is a conversion function which will never be called implicitly. The Standard actually goes into some depth about this. 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.
And in a footnote,
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.
Also, conversion functions are still normal functions and can be called explicitly by name.
The note about virtual functions applies to code like this:
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()
Pedantic note: "conversion operator" is poor terminology. These are known as conversion functions and they are not considered to be a case of operator overloading, despite the operator
keyword.
It's a conversion operator. It allows you to cast an object of type B
into an object of type B
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.