在C ++中向上和向下转换 [英] Upcast and Downcast in C++

查看:156
本文介绍了在C ++中向上和向下转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class文件{
std :: string name;
};

类目录:public file {
std :: vector< file *>条目;
};

目录d;
file f;

f = d; //只有d.name被复制到f;条目丢失

是这样的:

 目录* dp =新目录; 
file * fp;

fp = dynamic_cast< file *>(dp);

保留条目和身份作为目录对象或仍然只有 dp-> name 复制到 f ;



p>如果我们这样做会发生什么:

  dp = dynamic_cast< dp *> (fp)。 


解决方案

投放链接:
questionscompiled.com



Upcasting:
Upcast是将指针或引用的派生类类型的引用转换为基类类型的指针或引用,在继承树中向上移动。
向上转换有助于在C ++中实现接口概念。当一个函数被调用基类类型指针或引用(指向或引用它的一些派生类),该派生类的正确成员函数被调用。




Downcast是基类类型的指针或引用到其派生类的指针或引用类型的转换,在继承树中向下移动。这是通过在运行时安全地downcast的dynamic_cast运算符的帮助实现的。



这里是一个例子:

  class A 
{public:
int i;
virtual void show(){}
};

class B:public A
{
public:
int j;
virtual void show(){cout<<B; }
};

int main()
{
A * ptr = new B; // UPCAST​​ING
B * ptrb;
ptrb = dynamic_cast< B *>(ptr); // DOWNCASTING to derived object
ptrb-> show(); // upcasting帮助实现接口
}

参考上面的例子,dynamic_cast确保ptr指向类型B或其子类的对象。


class file {
    std::string name;
};

class directory : public file {
    std::vector<file*> entries;
};

directory d;
file f;

f = d; // Only d.name is copied to f; entries are lost

Is it if we do this:

directory* dp = new directory;
file* fp ;

fp = dynamic_cast<file*>(dp); 

Keeps entries and identity as a directory object or still only dp->name is copied to f; entries are lost.


Also, how does downcast work?

What happens if we do:

dp = dynamic_cast<dp*> (fp);

解决方案

Here is an explanation on what is up casting and down casting taken from link: questionscompiled.com

Upcasting: Upcast is conversion of pointer or reference of derived class type to pointer or reference of base class type, going up in the inheritance tree. Upcasting helps in achieving interfaces concept in C++. When a function is called on base class type pointer or reference(pointing or referring to some of its derived class), correct member function of that derived class gets invoked.

Downcasting: Downcast is the conversion of pointer or reference of base class type to pointer or reference type of its derived class, going down in the inheritance tree. This is achieved with help of dynamic_cast operator that safely downcast at run time.

Here is an example:

class A
{public:
  int i;
  virtual void show(){}
};

class B:public A
{
public:
  int j;
  virtual void show()  { cout<<"B";  }
};

int main()
{
  A* ptr=new B; // UPCASTING
  B* ptrb;
  ptrb=dynamic_cast<B*>(ptr); //DOWNCASTING to derived object
  ptrb->show(); // upcasting helped in implementing interface
}

With reference to above example, dynamic_cast ensures that ptr points to object of type B or its subclass.

这篇关于在C ++中向上和向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆