C++基础练习篇

C++的基础学习

#ifdef test_1

/*花括号的隐蔽性
结果:括号之外无法访问括号之内的变量*/
#include <iostream>

using namespace std;
int main(void)
{
    int out_value = 0;
    {
        int in_value = 1;
        out_value = 2;
    }
    std::cout << "out_value:" << out_value << std::endl;
    system("pause");
    return 0;
}
#endif

#ifdef test_2
/*测试const和引用的关系
结果:非const量不可以引用指向一个常量对象
const量可以引用一个变量并且变量属性变为const*/
#include <iostream>
/*引用的实验
引用的类型会影响被应用的对象的类型
如 const int out_value = f_value ,f_value的类型会变成const类型*/
using namespace std;
int main(void)
{
    int out_value = 0, a = 0;
    int &f_value = out_value;
    //auto &f_value = out_value; //系统自动分析表达式的类型,并把类型赋给f_value
    f_value = 2;

    //常量型引用指向变量,变量变为const型,并且不可被改变
    int i = 0;
    const int &b = i;
    //b = 3;
    i = 3;

    cout << "out_value:" << out_value << endl;
    system("pause");
    return 0;
}
#endif

#ifdef test_3
/*指针和const 的关系验证
如果是顶层const: int *cosnt p  = &a, 不允许修改z指针P的指向
如果是底层const: int cosnt *p  = &a, 允许修改z指针P的指向,不允许修改P所指向内容(&p不可被赋值)
a的属性不被影响*/
#include <iostream>

using namespace std;
int main(void)
{
    int out_value = 0, a = 0;
    int  *const p = &out_value;
    int  const *q = &out_value;
    //int  const *q = p;

    //p = &a; //错误执行,p的指向不可变
    *p = 2;   //正确执行,p指向的内容可变

    q = &a; //正确执行,q的指向可变
    //*q = 2; //错误执行,q指向的内容不可变
    a = 2; //正确执行,a的属性不会被改变
    cout << "out_value = " << out_value << endl;
    system("pause");
    return 0;
}
#endif


#ifdef test_4
/*测试常量表达式
结论:constexpr声明的表达式必须是常量表达式
补充:const声明指针底层的话,指针指向内容是常量
constexpr声明指针底层的话,指针本身是常量*/
#include <iostream>

using namespace std;
int main(void)
{
    int a = 0;
    constexpr int out_value = a;

    std::cout << "out_value:" << out_value << std::endl;
    system("pause");
    return 0;
}
#endif

#ifdef test_5
/*局部静态变量的生命周期验证

结果:整个程序运行周期内都存在*/
#include <iostream>
using namespace std;

void test(void)
{
    static int a = 0;
    a++;
    std::cout << "a:" << a << std::endl;
    return;
}

int main(void)
{
    test();
    test();
    test();
    system("pause");
    return 0;
}
#endif

#ifdef test_6
/*decltype的运用
如:decltyep(ci) r ;
r的类型是ci的类型*/
#include <iostream>
using namespace std;

void test(void)
{
    int i = 42, *p = &i, &r = i;
    decltype(r + 0) b; //int
    decltype(*p) c = i;  //c的类型是int& ,解引用操作的结果是 引用
    //decltype((i)) d = i;//实验失败,本来会是一个引用类型
    return;
}

int main(void)
{
    test();

    system("pause");
    return 0;
}
#endif
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值