码迷,mamicode.com
首页 > 其他好文 > 详细

cpp(布尔类型与引用)

时间:2019-02-22 22:59:08      阅读:516      评论:0      收藏:0      [点我收藏+]

标签:col   必须   div   style   初始   end   自动   语法   span   

/*
    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(布尔类型与引用)

标签:col   必须   div   style   初始   end   自动   语法   span   

原文地址:https://www.cnblogs.com/kenantongxue/p/10420826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!