簡體   English   中英

在 C++ 中使用宏重載運算符

[英]Operator overloading with macros in c++

嗨,我有一個關於宏的示例程序,

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

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

在上面的程序中,我試圖用MACRO 中的a 替換 -1,但是如果我嘗試用printf打印它,它可以工作!,但是如果我使用cout,它會拋出一個錯誤。 我知道這與“<<”運算符的重載有關,但我不知道確切原因。 請問有人可以解釋一下嗎? 提前致謝。

編輯:

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  

這是導致特定的錯誤嗎? 所以我的問題不是為什么我不應該使用MACROS ,我的問題是為什么printf給了我答案,為什么不 cout ?

了解宏是純文本替換,因此 cout 變為:

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

編譯進行搜索和替換,所以printf("%d",ABS(-1)); 變成printf("%d", (a) < 0 ? -(a) : (a))std::cout<<ABS(-1); 變成std::cout<<(-1) < 0 ? -(-1) : (-1) std::cout<<(-1) < 0 ? -(-1) : (-1) ,然后編譯就完成了。

<<優先級高於<所以std::cout<<(-1) < 0 ? -(-1) : (-1) std::cout<<(-1) < 0 ? -(-1) : (-1)等於(std::cout<<(-1)) < 0 ? -(-1) : (-1) (std::cout<<(-1)) < 0 ? -(-1) : (-1)

printf ,沒有像,printf那樣應用這樣的規則,它是參數的分隔符而不是運算符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM