简体   繁体   中英

To overload operator or make function (C++)

Which of the following is faster?

Method 1:

int foo (int A, int B) {

    // write equations
}

Method 2:

int operator| (int A, int B) {

    // write equations
}

There is no difference with respect to execution speed.

The choice is only one of style and readability. You should choose the one that makes for the most understandable code to help with future maintenance.

They are both a function (and thus have no difference in speed), just that the one (operator) can use a more "fancy" syntax to be invoked.

Your question when deciding what of the two to use should not be the speed, but rather if the meaning is natural to the type you use the operator on. When you use it to do something that would be totally surprising to the reader, considering he knows what the operator normally does, then don't overload the operator.

(I am assuming here you mean your own type instead of int, and just in case you didn't know, you can not overload operators on ints, one of the parameters for an overloaded operator must be a user defined type)

No difference, they're implemented exactly the same way internally in every compiler I've ever heard of. To be sure: profile it!

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