c++中所有关键字的解释

    技术2026-04-19  1

    inline

     

    比如在类中定义了一个属性size  是private私有的

    为了取该属性 我们定义一个方法:

    public int getSize(){

         return size;

    }

     

    当我们在main方法中调用getSize()时 编译方法时需要耗费一定的内存  可以使用关键字inline

    public int inline getSize(){

         return size;

    }

    比如在调用时

    int size=cls.getSize() 编译时 自动替换成 int size=cls.size  此时不需要方法这个过渡过程达到优化的目的

     

    explicit

     

    类上有构造方法

    Array(int size){}

     

    使用时 可以

    Array a=3 编译是绝对没有问题

     

    他的编译转换过程是:

    Array tmp(3);

    Array a=tmp;

    这个过程多了一个tmp对象

    所以为了优化防止这种情况 构造方法使用explicit关键字

    explicit Array(int size){}

    使用 Array a=3 这样写会出现编译错误

     

    operator

     

    比如定义了类中需要重载操作符 + - >> <<  [] 等

     

    比如重载[]

    class Array{

    string array[10];

    int length;

    string operator [](int index){

        return array[index];

    }

    void operator >>(string param){

        array[length-1]=param;

    }

    }

     

     使用时我们就可以  直接 string x=Array[0]

    Array a;

    a>>"对方答复对方";

     

    const

     

    const int i=0;

    表示i对象是不能被修改的 否则编译错误 

    比如企图修改 i=1 错误 const变量 必须要赋初始值

     

    const对象的指针和const指针

    const对象的指针就是可以指向任何对象但是不能修改指向对象的值

    const指针就是初始化指定指向某对象后 不能指向其他对象了 但是可以修改指定对象的值 

     

    const对象的指针:

     

    const int *pvalue=7;

    const int t=10;

    //const对象可以指向其他const对象 但是不能修改其他对象的值

    pvalue=&t;

    //下面是错的

    *pvalue=5;

     

    int g=100;

    //const对象可以指向其他非const对象 但是不能修改其他对象的值

    pvalue=&g;

    //这里修改它的值是错误的

    *pvalue=1;

     

     

    const指针

    int i=10;

    //指针指向了变量i  他就不能再指向其他地址 

    *const int j=&i;

     //但是他可以修改变量的值

    *j=10;

     

     

     

    register

     

    register int i;  使用register修饰的变量编译器可能会优化到寄存器中

    unsigned

    经常看到unsigned char 其实就是byte 无符号的整形 0-255之间

    而 signed char 就是从 -128 到127

    typeid和dynamic_cast

    首先在vc6下默认是未开启 运行时类别 也即是java中的intanceof js的typeof

    VC6中开启 选中 工程-》设置-》选中c/c++视图  Y分类中选择 C++ LANAGUAGE 勾选下面的 (I 允许时间类型信息RTTI)

    如果不勾选是允许时候 报错

    typeid必须作用于多态 父类中必须 存在virtual的函数

    通过以下代码 理解

    #include<iostream> using namespace std; class File { public:      void createFile(){          cout<<"创建文件"<<endl;      }      void deleteFile(){          cout<<"删除文件"<<endl;      }      virtual void openFile()=0;      ~File(){} }; class MediaFile:public File{ public:     void openFile(){         cout<<"打开媒体文件"<<endl;     } }; class TextFile:public File{ public:     void openFile(){         cout<<"打开文本文件"<<endl;     } }; void main(){     MediaFile med;     File* file=&med;     file->openFile();     cout<<typeid(*file).name()<<endl;     if(dynamic_cast<MediaFile*>(file)){         cout<<"通过dynamic_cast是MediaFile"<<endl;     }     if(typeid(*file)==typeid(MediaFile)){         cout<<"通过typeid判断是MediaFile"<<endl;     } }

    最新回复(0)