在 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 中的 -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)
.
在 printf
中没有像 printf
中的 ,
这样的规则可以应用,它是参数的分隔符而不是运算符。
嗨,我有一个关于宏的示例程序,
#include<iostream>
#define ABS(a) (a) < 0 ? -(a) : (a)
int main(){
printf("%d",ABS(-1));
std::cout<<ABS(-1);
return 0;
}
在上面的程序中,我试图用 MACRO 中的 -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)
.
在 printf
中没有像 printf
中的 ,
这样的规则可以应用,它是参数的分隔符而不是运算符。