简体   繁体   English

运算符重载自赋值

[英]operator overloading self assignment

can anyone please explain the below function.任何人都可以请解释以下功能。

  AddressBook& operator =(const AddressBook& bok);///add this two to your struct
    bool operator ==(const AddressBook& bok);///

/***************************************************************************************/
    ///anywhere outside main add this definitions

    bool AddressBook::operator ==(const AddressBook& bok)
    {
        return (firstname==bok.firstname&&lastname==bok.lastname&&addr==bok.addr&&phone==bok.phone);
    }

    AddressBook& AddressBook::operator=(const AddressBook& bok)
    {
        if(*this==bok)
            return *this;
        else
        {
            firstname=bok.firstname;
            lastname=bok.lastname;
            addr=bok.addr;
            phone=bok.phone;
        }
         return *this;
    }

There are two functions here.这里有两个功能。 Both of them overloading operators .它们都重载了运算符
The comparison operator for equality operator== will in this case compare two objects of type AddressBook .在这种情况下,相等operator==的比较运算符将比较AddressBook类型的两个对象。 It will return true (saying two addressbook objects are equal) when they match in firstname , lastname , addr and phone .当它们在firstnamelastnameaddrphone匹配时,它将返回true (说两个地址簿对象相等)。
The assignment operator will allow you to assign an AddressBook object to another, and it will copy over the values.赋值运算符将允许您将一个AddressBook对象分配给另一个对象,并且它将复制这些值。

if (*this = bok)
    return *this;

in this case checks if you assign an object to itself.在这种情况下,检查您是否将对象分配给自身。 In a class this pointy to the instance of the object.在类中this指向对象的实例。 In this case the left hand side of the = operator.在这种情况下, =运算符的左侧。 If they are the same (Meaning their address in memory is the same), then nothing is copied.如果它们相同(意味着它们在内存中的地址相同),则不会复制任何内容。
The = operator returns the value assigned. =运算符返回分配的值。 That is why things like这就是为什么事情像

a = b = 7;

are valid.是有效的。 b = 7 assigns 7 to b. b = 7b = 7分配给 b。 The operator returns the value 7. Then that return of 7 is assigned to a.运算符返回值 7。然后将返回的 7 分配给 a。 The return value of that operation is discarded.该操作的返回值被丢弃。
It is also the unfortunate reason why things like这也是令人遗憾的原因

int a = 5, b = 7;
if(a = b) // assignment, not comparison!
{ /*Do things*/ }

are valid.是有效的。 a is assigned the value of b , the return of the assignment-operation (the value of b , 7) is then used as the condition, which evaluates true. a被分配了b的值,然后将赋值操作的返回值( b的值,7)用作条件,该条件的计算结果为 true。 Even if you do want such a thing, it is bad style and should be written in two lines.即使你确实想要这样的东西,它也是糟糕的风格,应该写成两行。
All operators in c and c++ are function calls. c 和 c++ 中的所有运算符都是函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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