cpp(布尔类型与引用)

Posted kenantongxue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cpp(布尔类型与引用)相关的知识,希望对你有一定的参考价值。

/*
    bool 类型可以参与数学运算,在非0的情况下自动转变为1
*/

#include <iostream>
using namespace std;

int main()
{
    bool b = 0;

    cout << "b = " << b << endl;    //    b = 0

    b++;

    cout << "b = " << b << endl;    //    b = 1

    b = b - 3;

    cout << "b = " << b << endl;    //    b = 1

}

 

#include <iostream>
using namespace std;

int main()
{
    bool b = false;
    int a = b;

    cout << "sizeof(b) = " << sizeof(b) << endl;    //    sizeof()占用字节数,1
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    cout << "a与b改变数值后:" << endl;
    b = 3;
    a = b;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    cout << "a与b再次改变数值后:" << endl;
    b = -5;
    a = b;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

}

 

/*
    三目运算符既可以作为右值,也可以作为左值
    三目运算符可能返回的值中如果有常量值,则不能作为左值使用
*/

#include <iostream>
using namespace std;

int main()
{
    int a = 1;
    int b = 2;

    (a < b ? a : b) = 3;    //    a = 3;

    cout << "a = " << a
        << ", b = " << b << endl;

}
/*
    引用的使用,引用在定义时必须用同类型的变量进行初始化
    语法:
    type& name = var;
*/

#include <iostream>
using namespace std;

int main()
{
    int a = 4;
    int& b = a;    //    b为a的别名

    b = 5;    //    操作b就是操作a

    cout << "a = " << a << endl; 

}

 

#include <iostream>
using namespace std;

int main()
{
    int a = 4;
    int& b = a;
    
    b = 5;

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "&a = " << &a << endl;
    cout << "&b = " << &b << endl;

}

 

以上是关于cpp(布尔类型与引用)的主要内容,如果未能解决你的问题,请参考以下文章

转《js闭包与内存泄漏》

布尔类型及引用

Golang - 指针与引用

c_cpp Atlas300代码片段

c_cpp Robolution基本代码片段

js值类型与引用类型