0和1
非0值
,flase代表0
true(非0)
和flase(0值)
两个值非0值
转换为true
,0值
转换为flase
#include <iostream> using namespace std; int main() { bool a = 0; cout << "a = " << a << endl; a = 1; cout << "a = " << a << endl; a = 2; cout << "a = " << a << endl; a = -1; cout << "a = " << a << endl; } 结果: a = 0 a = 1 a = 1 a = 1
在C++对三目运算符进行了升级
分析下面代码:
test.c
#include <stdio.h> int main() { int a = 1; int b = 2; (a<b?a:b)=3; printf("a=%d,b=%d\n",a,b); return 0; } 结果: main.c: In function ‘main’: main.c:7:12: error: lvalue required as left operand of assignment 7 | (a<b?a:b)=3; | ^
test.cpp
#include <stdio.h> int main() { int a = 1; int b = 2; (a<b?a:b)=3; printf("a=%d,b=%d\n",a,b); return 0; } 结果: a=3,b=2
左值
使用,左值
也可以作为右值
,但是需要注意的是(a < b ? a : 2) = 3;
别名
一段连续的内存空间只能用一个别名吗?
答:可以用其他别名,即C++中的引用
int a = 4; int& b = a;//b为a的别名,a和b的类型都为int b = 5;//操作b相当于操作a
同类型的变量进行初始化
test.cpp
#include <iostream> int main() { int a = 4; int& b = a; std::cout << "a =" << a << std::endl; std::cout << "b =" << b << std::endl; std::cout << "&a ="<< &a << std::endl; std::cout << "&b =" << &b << std::endl; return 0; } 结果: a =4 b =4 &a =00BCFC00 &b =00BCFC00
当a和b类型不同时:将
float& b = a;
在vs2019中直接报错
int a = 1; int b = 2; (a < b?a:b)=3;//正确,返回a或者b的引用,可以作为左值 (a < b?1:b)=3;//错误,返回1或者b的值,不能作为左值