简体   繁体   中英

Operator overloading with macros in c++

Hi i have a sample program on macros,

#include<iostream>
#define ABS(a) (a) < 0 ? -(a) : (a)

int main(){
    printf("%d",ABS(-1));
    std::cout<<ABS(-1);
    return 0;
}

In the above prgram i was trying to subsititute -1 with a in MACRO but if i try to print it with printf it works!, But if i use cout it throws up an error. I know it is related to overloading of "<<" operator, But i dont know the exact reason. Please can someone explain? Thanks in advance.

Edit:

Severity    Code    Description Project File    Line    Suppression State
Error   C2678   binary '<': no operator found which takes a left-hand operand of type 'std::basic_ostream<char,std::char_traits<char>>' (or there is no acceptable conversion)  practice_project    C:\Users\source\repos\practice_project\Source.cpp   10  

This was the error caused to be specific? So my question is not on why i should not use MACROS , my question is why printf gave me the answer and why not cout?

Understand that macros are pure text substitution, so the cout becomes:

std::cout<<(-1) < 0 ? -(-1) : (-1);

Macros do a search and replace before compiling, so printf("%d",ABS(-1)); becomes printf("%d", (a) < 0 ? -(a) : (a)) , and the std::cout<<ABS(-1); becomes std::cout<<(-1) < 0 ? -(-1) : (-1) std::cout<<(-1) < 0 ? -(-1) : (-1) , and then the compiling is done.

<< ha a higher precedence then < so the std::cout<<(-1) < 0 ? -(-1) : (-1) std::cout<<(-1) < 0 ? -(-1) : (-1) is equal to (std::cout<<(-1)) < 0 ? -(-1) : (-1) (std::cout<<(-1)) < 0 ? -(-1) : (-1) .

In printf there is no such rule to apply as the , in the printf that is the separator of the arguments and not an operator.

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