And logic with logic or overloading

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/dxd_123456/article/details/78066870

&& and || are C ++ very special operator, && and || built to achieve a short-circuit rules, operator overloading rely on overloading to complete operand as a function of transmission parameters, C ++ function parameters will be evaluated, not short-circuit the rules. And so it will not reload logic or logic in general.
Here with a case to analyze why do not overload or logic and logic.

#include <stdio.h>
class Test8
{
public:
    Test8(int a)
    {
        m_a = a;
    }

    bool operator&&(Test8 &obj)
    {
        return (m_a && obj.m_a);
    }
private:
    int m_a;
};

int main()
{
    Test8 a(10), b(0), c(30);
    b && (a = c);
    printf("a = %d, b = %d, c = %d\n", a, b, c);
    return 0;
}

Overloaded function can be logically and operation, there is no effect on the results, but we can not simulate the real logical process and the implementation of the above program, if not overloaded && use, but simply the digital computing, that is defining integral data a = 10, b = 0, c = 30; operation then b && (a = c), the result in this case is b = 0, a = 10, c = 30; apparent later assignment a = c is not performed, the principle of which is short-circuited with built-in logic, as before is 0 && is, on the end not perform the following operations;
whereas if overloaded functions, an object is && operation, At this time, the result is a = 30, b = 0, c = 30, can be found behind the assignment is carried out, and why?
We know, && is overloaded by overloading to complete operand as a function of transmission parameters, then the above b && (a = c) can be rewritten as the operation b.operator && (a = c)
it is clear that the process does not there will be a short circuit principle. So overloaded && && operator is not operating in the true sense, the same || operator is like this, do not overload && and || operators under the normal circumstances.

Guess you like

Origin blog.csdn.net/dxd_123456/article/details/78066870