简体   繁体   中英

operator overloading [operator A() const]

There is a pre-defined class named B as under:

class B
{
    protected:
        A ins;
    public:
        void print() {
            cout<<"t";
        }
        operator A() const {
            return ins; 
        }
};

Can anyone please explain the meaning of the line "operator A() const" and how can this be used to fetch "ins" in the main function?

This is a conversion operator that allows B objects to be converted to (cast to) A objects. Let's break down operator A() const {...}

It is equivalent to something like A convert_to_A() { return ins; } A convert_to_A() { return ins; } except that by naming it operator A the compiler can use it automatically.

operator A means that this is an operator that converts to type A.

() : conversion operators are always function that take no parameters .

const because casting a B to an A must not change the value of the B . For example:

double d = 3.14;
int i = d;

Here d has been (implicity) cast to an int. i has the value 3, but d is still 3.14 -- the conversion did not change the original value.

In the context of your code we can say:

  1. a B object contains a hidden A object
  2. each B is willing to "pretend" to be an A ...
  3. ... by returning a copy of the A inside it

Allowing:

void f(A an_a) {...}

B my_b;
f(my_b);

Note that the conversion operator returns a copy of ins . Depending on context, you might want to change it to operator A&() const {...} to return a reference instead of a copy (if, for example, A was an expensive class to copy). However, this would allow the caller to change the A stored inside B, which is probably not want you want. To prevent the copy, but not allow changes, you would have to return a const reference to A. This is why you'll often see:

operator const A&() const { return ins;}

This mean you can cast your B instance to A and get the ins member of B.

B b;
A a;

a = (A)b;

// a is now equal to the member `ins` of b. Depending on the implementation of operator = of class A, it was probably copied into the a variable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM