C++ 关键字

来源:互联网 发布:交通组织优化方案 编辑:程序博客网 时间:2024/06/14 22:16

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

mutable

const 对应

//from msdnclass 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/explicitstruct 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 msdnclass 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 Derivedclass Derived *class Derived*/

typename

和template一起用,作用同class

template <class T>class C1 : typename T::InnerType{};template <class T>class C2 : A<typename T::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<int*>(&a);//compile error    *b=2;    cout<<a<<endl;//1    cout<<*b<<endl;//2    cout<<(&a==b)<<endl;//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

0 0