C++ 之and, and_eq, or, or_eq, xor, xor_eq, not, not_eq操作符

在C++ 有一些不太受关注的关键字,这些关键字也是操作符:

and, and_eq, or, or_eq, xor, xor_eq, not, not_eq, bitand, bitor

and

表示逻辑与操作, 是C++原有操作符 && 的等效替换

bool success1 = execute_some_task();
bool success2 = execute_another_task();
if(success1 and success2)
{
	std::cout << "two tasks have been done successfully" << std::endl;
}

and_eq

表示相与并赋值,等价于 &= 操作符

unsigned char a = 0xFE;
unsigned char b = 0x02;
b and_eq a; // 等价于 b &= a;
std::cout << "new b is " << b << std::endl;

or

逻辑或, 等价于 || 操作符

int year = 2017;
//等价于 bool result = a % 400 == 0 || a % 400 != 0 && a % 4 == 0; 
bool result = a % 400 == 0 or a % 400 != 0 and a % 4 == 0;  

or_eq

相或并赋值,等价于 |= 操作符

unsigned short port = 0x0000;
port or_eq 0xFFEE; //等价于 port |= 0xFFEE;

xor

逻辑异或, 登记于 ^

int a = 0x5A xor 0xCE; //等价于 int a = 0x5A ^ 0xCE;

xor_eq

相异或并赋值

int a = 10;
int b = 15;
a xor_eq b xor_eq a xor_eq b; //等价于 a ^= b ^= a ^=b; 

not

逻辑非, 等价于操作符 !

bool islast = true;
if(not isLast)  //等价于 if(!isLast)
{
	// todo
}

bitand, bitor

与and,or类似,不过是按位操作, bitand等价于& , bitor 等价于 |

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页