所谓替代运算符无非就是用其他字符或者符号代表一些预定义的运算符和符号
有如下代码
int main(int x, char**)
{
}
如果用替代用算符表示的话
int main(int x, char**)
<% %>
就是这样,花括号可以替换成了为<% %>,无非就是换了一个表示方法
在C++到20可以使用的代用符如下
符号 | 替换符 |
---|---|
&& | and |
&= | and_eq |
& | bitand |
| | bitor |
~ | compl |
! | not |
!= | not_eq |
|| | or |
|= | or_eq |
^ | xor |
^= | xor_eq |
{ | <% |
} | %> |
[ | <: |
] | :> |
# | %: |
## | %:%: |
综合使用如下
#include <stdio.h>
#include <iostream>
using namespace std;
%:define abc 1 //#
#define ccc(v) cout <<v%:%:v<< "\r\n"; //%:%:
int main(int x, char**)
<% bool a = false and true;// &&a = not false;// !a = a not_eq false;// !=a = false or true;// ||a or_eq false;// |=int n=1;n and_eq 1;//&=n = n bitand 1;//& n = n bitor 1;// |n = compl n;// ~n = 1 xor 2;//^n xor_eq 2;// ^=<%//{int c<:3:> = {1,2,3}; //[]%>//}printf("%d",abc);ccc(6);
%>
要注意的是,在c++17以后,下面几个替换运算符,已经不能使用了
符号 | 替换符 |
---|---|
{ | ??< |
} | ??> |
[ | ??( |
] | ??) |
# | ??= |
\ | ??/ |
^ | ??’ |
| | ??! |
~ | ??- |
事实上这些符号,我们也可以通过宏定义来做到,比如想把括号替换KuoHaoL ,KuoHaoR
#define KuoHaoL (
#define KuoHaoR )
int main KuoHaoL int x, char** KuoHaoR
{return 1;
}
以上的运算符都是在C++中语法定义的,实际上在C中就使用宏定义方式,实现了一些
#define and &&
#define and_eq &=
#define bitand &
#define bitor |
#define compl ~
#define not !
#define not_eq !=
#define or ||
#define or_eq |=
#define xor ^
#define xor_eq ^=