简体   繁体   中英

Why does the assignment operator return anything to begin with?

I know that the "+" operator has to return something, and that makes sense to me.

But what I don't understand is why we return an object when overloading the "=" operator. For example look at the following:

const Scene& Scene::operator=(const Scene &source){
    if(this != &source){
         count = source.count
    }
    return *this;
}

Can't we just achieve the same effect by just using this?

void Scene::operator=(const Scene &source){
    if(this != &source){
         count = source.count
    }
}

The semantics of the = operator are that you can chain assignments:

a = b = c;

You have to return an object for that to make sense.

You can return a reference, and that supports assignment chaining like in

a = b = 42;

… which, since = is right-associative, is parsed as

a = (b = 42);

… so that both a and b are set to 42 .

However you don't have to let your assignment operator return anything, unless you want to support use of your objects in a standard library collection.

Unfortunately the standard library requires that an item in a collection, if it is required to be assignable, must offer an assignment operator that returns a reference to the object.

Also you need to use that form of declaration in order to delete or default an assignment operator for your class.

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