C++ 关键字

2019-04-14 19:14发布

电面被问到,没答出。于是。。。
比较少用到的

mutable

const 对应 //from msdn class X { public: bool GetFlag() const { m_accessCount++; return m_flag; } private: bool m_flag; mutable int m_accessCount; };

explicit

//from http://en.cppreference.com/w/cpp/language/explicit struct A { A(int) { } // converting constructor A(int, int) { } // converting constructor (C++11) operator bool() const { return true; } }; struct B { explicit B(int) { } explicit B(int, int) { } explicit operator bool() const { return true; } }; int main() { A a1 = 1; // OK: copy-initialization selects A::A(int) A a2(2); // OK: direct-initialization selects A::A(int) A a3 {4, 5}; // OK: direct-list-initialization selects A::A(int, int) A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int) A a5 = (A)1; // OK: explicit cast performs static_cast if (a1) ; // OK: A::operator bool() bool na1 = a1; // OK: copy-initialization selects A::operator bool() bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization // B b1 = 1; // error: copy-initialization does not consider B::B(int) B b2(2); // OK: direct-initialization selects B::B(int) B b3 {4, 5}; // OK: direct-list-initialization selects B::B(int, int) // B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int) B b5 = (B)1; // OK: explicit cast performs static_cast if (b2) ; // OK: B::operator bool() // bool nb1 = b2; // error: copy-initialization does not consider B::operator bool() bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization }

typeid

//from msdn class Base { public: virtual void vvfunc() {} }; class Derived : public Base {}; using namespace std; int main() { Derived* pd = new Derived; Base* pb = pd; cout << typeid( pb ).name() << endl; cout << typeid( *pb ).name() << endl; cout << typeid( pd ).name() << endl; cout << typeid( *pd ).name() << endl; delete pd; return 0; } /*output: class Base * class Derived class Derived * class Derived */

typename

和template一起用,作用同class template T> class C1 : typename T::InnerType {}; template T> class C2 : AT::InnerType>...

四个cast

static_cast 和 dynamic_cast

dynamic_cast主要用于类层次间的上行转换和下行转换,还可以用于类之间的交叉转换。
在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。

const_cast

似乎可以把 非const 转为 constconst 转为 非const
不过只能对 指针引用 操作 const int a=1; int*b=const_cast<int*>(&a); //int*c=static_cast(&a);//compile error *b=2; cout<//1 cout<<*b<//2 cout<<(&a==b)<//1

reinterpret_cast

没弄明白。。。 参考:
http://www.cnblogs.com/fanzhidongyzby/archive/2012/11/07/2759326.html
http://www.cnblogs.com/chio/archive/2007/07/18/822389.html