Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Why should you be careful of the equality operator of the base class in C++

Shulou Source: shulou.com Published: 2022-06-01 19:12:11 10月03日 Update

This article mainly explains "Why should be careful of the equality operator of the base class in C++". The explanation in the article is simple and clear and easy to learn and understand. Please follow the editor's train of thought. Let's study and learn why we should be careful of the equality operator of the base class in C++.

Reason (reason)

It's really hard to write simple and easy-to-use equality operators for inheritance systems.

Example, bad (negative example) class B {

String name

Int number

Virtual bool operator== (const Ba) const

{

Return name = = a.name & & number = = a.number

}

/ /...

}

The second Operand of the equality comparison operator of B accepts type conversions, but the first one does not.

Class D: B {

Char character

Virtual bool operator== (const Da) const

{

Return name = = a.name & & number = = a.number & & character = = a.character

}

/ /...

}

B b =.

D d =.

B = = d; / / compares name and number, ignores d's character

D = = b; / / error: no = = defined

D d2

D = = D2; / / compares name, number, and character

B & b2 = D2

B2 = = d; / / compares name and number, ignores d2s and d's character

Of course, there is a way to make the equality comparison operator act in the inheritance system, but the simple method is not.

Note (Note)

This rule applies to all common comparison operators:! =, =.

Enforcement (implementation recommendations)

The hint is defined as the equality comparison operator of the virtual function; the same is true of other comparison operators:! =, =.

Thank you for your reading, the above is the content of "Why should be careful of the equality operator of the base class in C++". After the study of this article, I believe you have a deeper understanding of the question of why you should be careful of the equality operator of the base class in C++, and the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Operators operations clocking learning no systems contents functions methods actions causes negative that is common suggestions ideas situations operands articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Xiaomi macOS Shulou Technology vpn