C++中的几个冷僻关键字

来源:互联网 发布:手机制冷软件 编辑:程序博客网 时间:2024/04/29 00:19

(1)typeid
用于在运行时获取一个对象的类型,相当于函数原型:

const type_info &typeid(TYPE or expr);Base* pb = new Derived;cout << typeid( pb ).name() << endl;  //prints "class Base *"cout << typeid( *pb ).name() << endl; //prints "class Derived"


 

(2)typename
主要用在模板函数(类)中,为了避免 class 可能带来的误会。
template<class TYPE> 等价于 template<typename TYPE>

(3)volatile
告诉编译用到这个变量时,该变量随时可能被外部改变,每次使用时都必须重新读取,而不是使用保存在寄存器里的备份。
如 volatile long ref;

(4)explicit
据MSDN: 该关键字用于修饰类的构造函数,用来禁止隐式转换。

class String{public: explicit String(const char *s); explicit String(const String &s);};String s1("abc"), s2(s1); //总是合法的用法String s1 = "abc", s2 = s1; //explicit时才会禁止


 

(5)mutable
据MSDN: 该关键字只能用于修饰类的非静态、非常量的成员变量,使得 const 成员函数内可以修改该成员变量。

class String{public: void func() const {  m_num = 1; }private: mutable long m_num;};


 

原创粉丝点击