C++引用,常量优化,四种类型转换符

变量引用变量的别名,常量引用要加const,引用与被引用的东西是同一样。

#include <string>    
#include <ctype.h>
#include <vector>
#include <iostream>  
#include <fstream>


// using declarations states our intent to use these names from the namespace std    
using namespace  std;

int main()
{
    int var = 3;
    int &r_var = var; //变量
    const int &r_var1 = 123; //常量的引用要加const表明r_var1是const int类型的引用
    const int &r_var1 = var+123; //var+123 中间变量的引用
    int &r_var2 = r_var;//引用后同样也可以引用
    return 0;
}

c++在内部进行了大量的优化工作,如果给一个值声明为const,那么以后每次读取都不会重新从内从中读取数据加快常量访问速度,只会读取第一次给定的值

但是volatile关键字可以改变const的这种性质,在定义后的每次读取数据中都会重新从内存中读取。

#include <string>    
#include <ctype.h>
#include <vector>
#include <iostream>  
#include <fstream>


// using declarations states our intent to use these names from the namespace std    
using namespace  std;

int main()
{
    const int n = 100; //后面使用n的值都用100代替
    volatile const int m = 200; //m以后每次使用都从内存中读取

    int *p = (int *)&n;
    *p = 110;
    cout << "n = " <<n << endl; //输出100,n没有改变
//这里我想说n其实不是没有改变,如果进入内存中n的地址的时候,会发现其存储的值是110,只是c++做了优化,不再读取内存的值 p
= (int *)&m; *p = 210; cout << "m = " << m << endl; //输出210,m被改变 return 0; }

C++提供了四种类型转换符,规定这四种转换符是为了明确转换的目的。

#include <string>    
#include <ctype.h>
#include <vector>
#include <iostream>  
#include <fstream>


// using declarations states our intent to use these names from the namespace std    
using namespace  std;

int main()
{
    /*
    第一,之所以设置的那么长那么丑是为了防止程序员使用,c++中不建议用强制类型转换,设置好对的类型就不需要转换
    第二,为了方便找到程序中哪里用到了强制类型转换
    
    static_cast; 用于数值类型的转换,以及有一方是void*类型的转换
    const_cast;用于临时去掉const, volatile限制,转换用于语句本身,出了语句就没有了,进行常变量的转换
    reinterpret_cast;用于任意两种指针之间,以及指针与数值类型之间的转换,最危险
    dynamic_cast;用于父子类之间的转换
    */

    //int n = 12.34; //会有警告
    int n = static_cast<int>(12.34);//无警告
    //int *p = calloc(sizeof(int), 10); //错误
    int *p = static_cast<int*>(calloc(sizeof(int), 10));
    
    const int k = n; //这里c++不会优化,因为n本来就是变量,而不是具体的数值,没优化的必要
    const_cast<int&>(k); //将k转换为int类型,但是由于这种转换只对这条语句有用,那么我们这采用引用来保持这种转换

    float f = 12.34;
    p = reinterpret_cast<int *>(&f);
    cout << "p's value is " << *p << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/yican/p/3915350.html