专业转换运算符dynamic_cast

dynamic_cast <new_type> (expression)

dynamic_cast运算符,应该算是多少个里头最新鲜的一个,因为它涉及到编译器的性能设置,而且牵扯到的面向对象的多态性跟程序运行时的情形也有涉及,所以无法完全的使用传统的更换格局来替代。可是也由此它是最常用,最不可缺失的一个运算符。

static_cast一样,dynamic_cast的变换也急需目的项目和源对象有肯定的关系:继承关系。
更确切的说,dynamic_cast是用来检查两者是否有连续关系。由此该运算符实际上只接受基于类对象的指针和引用的类转换。从那多少个下边来看,似乎dynamic_cast又和reinterpret_cast澳门新葡萄京官网注册,是一样的,但事实上,它们或者存在着很大的距离。

仍旧用代码来表达,让编译器来表明呢。

/////////////////////////////////////////////////////////////////////////////
// cast_operator_comparison.cpp                                                      
// Language:   C++                   
// Complier:    Visual Studio 2010, Xcode3.2.6 
// Platform:    MacBook Pro 2010
// Application:  none  
// Author:      Ider, Syracuse University  ider.cs@gmail.com
///////////////////////////////////////////////////////////////////////////
#include <string>
#include <iostream>
using namespace std;

class Parents
{
public:
    Parents(string n="Parent"){ name = n;}
    virtual ~Parents(){}

    virtual void Speak()
    {
        cout << "\tI am " << name << ", I love my children." << endl;
    }
    void Work()
    {
        cout << "\tI am " << name <<", I need to work for my family." << endl;;
    }
protected:
    string name;
};

class Children : public Parents
{
public:
    Children(string n="Child"):Parents(n){ }

    virtual ~Children(){}

    virtual void Speak()
    {
        cout << "\tI am " << name << ", I love my parents." << endl;
    }
    /*
     **Children inherit Work() method from parents,
     **it could be treated like part-time job.
     */
    void Study()
    {
        cout << "\tI am " << name << ", I need to study for future." << endl;;
    }

private:
    //string name; //Inherit "name" member from Parents
};

class Stranger 
{
public:
    Stranger(string n="stranger"){name = n;}
    virtual ~Stranger(){}

    void Self_Introduce()
    {
        cout << "\tI am a stranger" << endl;
    }
    void Speak()
    {
        //cout << "I am a stranger" << endl;
        cout << "\tDo not talk to "<< name << ", who is a stranger." << endl;
    }
private:
    string name;
};

int main() {

    /******* cast from child class to base class *******/
    cout << "dynamic_cast from child class to base class:" << endl;
    Children * daughter_d = new Children("Daughter who pretend to be my mother");
    Parents * mother_d = dynamic_cast<Parents*> (daughter_d); //right, cast with polymorphism
    mother_d->Speak();
    mother_d->Work();
    //mother_d->Study(); //Error, no such method

    cout << "static_cast from child class to base class:" << endl;
    Children * son_s = new Children("Son who pretend to be my father");
    Parents * father_s = static_cast<Parents*> (son_s); //right, cast with polymorphism
    father_s->Speak();   
    father_s->Work();
    //father_s->Study(); //Error, no such method

    cout << endl;

    /******* cast from base class to child class *******/    
    cout << "dynamic_cast from base class to child class:" << endl;
    Parents * father_d = new Parents("Father who pretend to be a my son");
    Children * son_d = dynamic_cast<Children*> (father_d); //no error, but not safe
    if (son_d)
    {
        son_d->Speak();
        son_d->Study();
    }
    else cout << "\t[null]" << endl;

    cout << "static_cast from base class to child class:" << endl;
    Parents * mother_s = new Parents("Mother who pretend to be a my daugher");
    Children * daughter_s = static_cast<Children*> (mother_s);  //no error, but not safe
    if (daughter_s)
    {
        daughter_s->Speak();
        daughter_s->Study();
    }
    else cout << "\t[null]" << endl;

    cout << endl;

    /******* cast between non-related class *******/  
    cout << "dynamic_cast to non-related class:" << endl;
    Stranger* stranger_d = dynamic_cast<Stranger*> (daughter_d);
    if (stranger_d)
    {
        stranger_d->Self_Introduce();
        stranger_d->Speak(); 
    }
    else cout <<"\t[null]"<<endl;

    //Stranger* stranger_s = static_cast<Stranger*> (son_s);    //Error, invalid cast

    cout << "reinterpret_cast to non-related class:" << endl;
    Stranger* stranger_r = reinterpret_cast<Stranger*> (son_s);
    if (stranger_r)
    {
        stranger_d->Self_Introduce();
        //stranger_d->Speak(); //This line would cause program crush,
        //as "name" could not be found corretly.
    }
    else cout << "\t[null]" << endl;

    cout << endl;

    /******* cast back*******/
    cout << "use dynamic_cast to cast back from static_cast:" << endl;
    Children* child_s = dynamic_cast<Children*> (father_s);
    if (child_s)
    {
        child_s->Speak();
        child_s->Work();
    }
    else cout << "\t[null]" << endl;

    //cout<<typeid(stranger_r).name()<<endl;

    cout << "use dynamic_cast to cast back from reinterpret_cast:" << endl;
    Children* child_r = dynamic_cast<Children*> (stranger_r);
    if (child_r)
    {
        child_r->Speak();
        child_r->Work();
    }
    else cout << "\t[null]" << endl;

    delete daughter_d;
    delete son_s;
    delete father_d;
    delete mother_s;

    return 0;
}

/********************* Result *********************/

//dynamic_cast from child class to base class:
//    I am Daughter who pretend to be my mother, I love my parents.
//    I am Daughter who pretend to be my mother, I need to work for my family.
//static_cast from child class to base class:
//    I am Son who pretend to be my father, I love my parents.
//    I am Son who pretend to be my father, I need to work for my family.
//
//dynamic_cast from base class to child class:
//    [null]
//static_cast from base class to child class:
//    I am Mother who pretend to be a my daugher, I love my children.
//    I am Mother who pretend to be a my daugher, I need to study for future.
//
//dynamic_cast to non-related class:
//    [null]
//reinterpret_cast to non-related class:
//    I am a stranger
//
//use dynamic_cast to cast back from static_cast:
//    I am Son who pretend to be my father, I love my parents.
//    I am Son who pretend to be my father, I need to work for my family.
//use dynamic_cast to cast back from reinterpret_cast:
//    [null]

从上边的代码和出口结果可以看出:

对于从子类到基类的指针转换,static_cast和dynamic_cast都是马到成功还要正确的(所谓成功是说转换没有编译错误或者运行很是;所谓科学是指方法的调用和数量的访问输出是可望的结果),这是面向对象多态性的周详显示。

而从基类到子类的变换,static_cast和dynamic_cast
都是水到渠成的,不过正确性方面,我对双方的结果都先举办了是否非空的鉴别:dynamic_cast的结果突显是空指针,而static_cast则是非空
指针。但很明确,static_cast的结果应该算是错误的,子类指针实际所指的是基类的对象,而基类对象并不有所子类的Study()方法(除非二姨又想去接受个”继续教育”)。

对此从未涉及的六个类之间的转换,输出结果注明,dynamic_cast还是是回来一个空指针以代表转换是不树立的;static_cast直接在编译期就不肯了这种转移。

reinterpret_cast成功举行了更换,而且回去的值并不是空指针,但是结果肯定是大错特错的,因为Children类显著不负有
Stranger的Self_Introduce()。固然双方都有所name数据成员和Speak()方法,,Speak()方法也只是调用了该相同名
称的成员而已,不过对于Speak()的调用直接促成了程序的垮台。

实质上前边static_cast的转移的结果也会跟reinterpret_cast一样导致的程序的崩溃,只是类的主意都只有一份,只有多少成员属于对象,
所以在调用这个不会造访对象的数码的章程时(如Stranger的Self_Introduce())并不会导致崩溃。而
daughter_s->Speak();和daughter_s->Study();调用了数量成员却没有出现运行错误,则是因为该成员是
从基类继承下去的,通过地方偏移能够正确的抵达数据成员所在的地方以读取出数据。

末尾,程序里还用dynamic_cast希望把用其他转换运算符转换过去的指针转换回来。
对于利用static_cast转换后指向了子类对象的基类指针,dynamic_cast判定转换是成立可行的,由此转换成功收获一个非空的指针并且正
确输出了结果;而对于reinterpret_cast转换的类型,的确如它的功力雷同——重新分析,变成新的项目,所以才取得dynamic_cast
判定该项目已经不是原先的档次结果,转换得到了一个空指针。

必须说来,static_cast和reinterpret_cast运算符要么直接被
编译器拒绝举办转换,要么就决然会得到相应的靶子项指标值。
而dynamic_cast却会举行识别,确定源指针所指的内容,是否确实适合被目标指针接受。如果是否认的,那么dynamic_cast则会再次来到null。那是经过检查“运行期类型音讯”(Runtime type
information,RTTI)
来判定的,它还受到编译器的影响,有些编译器需要安装开启才能让程序正确运行(导师的PPT详见介绍了Visual
Studio的境况),由此dynamic_cast也就不能够用传统的转移形式来落实了。

虚函数(virtual function)对dynamic_cast的作用

业已在前头反复提到过面向对象的多态性,不过那多少个多态性到底要哪些显示吗?dynamic_cast真的同意擅自对象指针之间展开转移,只是末了回来个null值来报告转换无结果吧?

事实上,这一切都是虚函数(virtual
function)
在起效能。

在C++的面对对象考虑中,虚函数起到了很关键的职能,当一个类中颇具至少一个虚函数,那么编译器就会构建出一个虚函数表(virtual
method
table)
来提醒这一个函数的地址,要是继承该类的子类定义并促成了一个同名并有所相同函数签名(function
siguature)
的办法重写了基类中的方法,那么虚函数表会将该函数指向新的地点。此时多态性就反映出来了:当我们将基类的指针或引用指向子类的靶子的时候,调用方法时,就会沿着虚函数表找到呼应子类的措施而非基类的措施。

自然虚函数表的留存对于功能上会有自然的震慑,首先构建虚函数表需要时间,依照虚函数表寻到到函数也亟需时刻。

因为这么些原因一旦没有持续的需要,一般不要在类中定义虚函数。然而对于持续来说,虚函数就变得很重要了,这不仅仅是实现多态性的一个首要标志,同时也是dynamic_cast转换可以举办的前提条件。

假使去掉上个例子中Stranger类析构函数前的virtual,那么语句
Children* child_r = dynamic_cast<Children*> (stranger_r);

在编译期就会间接报出荒谬,具体原因不是很领悟,我估量可能是因为当类没有虚函数表的时候,dynamic_cast就无法用RTTI来规定类的具体品种,于是就径直不通过编译。

这不仅仅是尚未持续关系的类之间的事态,要是基类或者子类没有其他虚函数(若是基类有虚函数表,子类当然是自动连续了该表),当他俩作为dynamic_cast的源类型进行转移时,编译也会失败。

这种处境是有可能存在的,因为在计划的时候,大家或许不需要让子类重写任何基类的艺术。但实际,这是不客观的。导师在教学多态性的时候,时刻强调了好几:假如要用继承,那么一定要让析构函数是虚函数;假设一个函数是虚函数,那么在子类中也如若虚函数。

我会将讲师关于”为啥连续中析构函数必须是虚函数”的执教总括一下,当然你也足以看那边作品来了然原因。

Director: Jim
Fawcett

  1. C++ Language Tutorial – Type
    Casting
  2. Object Oriented
    Design
  3. IBM Complilers – XL C/C++ V9.0 for Linux – The dynamic_cast
    operator (C++
    only)
  4. MSDN Visual C++ Develope Center – dynamic_cast
    Operator
  5. In C++, what’s a virtual destructor and when is it
    needed?
  6. Wikipedia The Free Encyclopedia – Run-Time Type
    Information
  7. Wikipedia The Free Encyclopedia – Virtual
    Function


http://www.cnblogs.com/ider/archive/2011/08/01/cpp\_cast\_operator\_part5.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注