开发者

How to support (a = b) = c?

开发者 https://www.devze.com 2023-03-27 09:35 出处:网络
Question 1> what does the following code meaning and what the order of assignment is? ClassName a1, a2, a开发者_开发问答3;

Question 1> what does the following code meaning and what the order of assignment is?

ClassName a1, a2, a开发者_开发问答3;
a1 = a2 = a3;

Does it mean to First assign value of a3 to a2 and then assign ?? to a1.

Question 2> what does the following code meaning?

ClassName a1, a2, a3;
(a1 = a2) = a3;

Question 3> Given a class as follows:

class A
{
   ...
}

What operators have to be defined in order to support the following operation?

A a1, a2, a3;
(a1 = a2) = a3;


Question 1

This:

a1 = a2 = a3;

is equivalent to this:

a1 = (a2 = a3);

For primitive types, or for PODs, this is equivalent to:

a2 = a3;
a1 = a2;

For user-defined types, it's equivalent to:

a1.operator=(a2.operator=(a3));

If you don't define your own overloads of operator=, then this will be the same as for the primitive types.

Question 2

This:

(a1 = a2) = a3;

only works for user-defined types. It is equivalent to:

a1.operator=(a2).operator=(a3);

If you use the compiler-provided operators, then this is equivalent to:

a1 = a2;
a1 = a3;

Question 3

No operators have to be defined, as the compiler provides a copy-assignment operator implementation if you don't write your own.


Question 1:

Evaluation order is performed from right to left, so a1 = a2 = a3 is equivalent to a2 = a3; a1 = a2;

Question 2:

If operator= has not been redefined, it means a1 = a3.

Question 3:

Nothing, it works as is.

0

精彩评论

暂无评论...
验证码 换一张
取 消