为什么在c++中选择dynamic_cast
Why to opt for dynamic_cast in C++
考虑以下代码:
#include <iostream>
using namespace std;
class Base{
int i;
public:
virtual bool baseTrue() {return true;}
Base(int i) {this->i=i;}
int get_i() {return i;}
};
class Derived : public Base{
int j;
public:
Derived(int i,int j) : Base(i) {this->j=j;}
int get_j() {return j;}
};
int main()
{
Base *bp;
Derived *pd,DOb(5,10);
bp = &DOb;
//We are trying to cast base class pointer to derived class pointer
cout << bp->get_i() << endl;
cout << ((Derived *)bp)->get_j() << endl;**//HERE1**
pd=dynamic_cast<Derived*> (bp); **//HERE2**
// If base class is not polymorphic
//throw error
//error: cannot dynamic_cast `bp' (of type `class Base*') to
//type `class Derived*' (source type is not polymorphic)
cout << pd->get_j() << endl;**//HERE2**
//Now we try to cast derived Class Pointer to base Class Pointer
Base *pb;
Derived *dp,Dbo(50,100);
dp = &Dbo;
cout << ((Base *)dp)->get_i() << endl;**//HERE3**
//cout << ((Base *)dp)->get_j() << endl;
//throws error Test.cpp:42: error: 'class Base' has no member named 'get_j'
pb = dynamic_cast<Base * > (dp); **//HERE4**
cout << pb->get_i() << endl; **//HERE4**
//cout << pb->get_j() << endl;
//throws error Test.cpp:47: error: 'class Base' has no member named 'get_j'
return 0;
}
输出Gaurav@Gaurav-PC /cygdrive/d/Glaswegian/CPP/Test
$ ./Test
5
10
10
50
50
我使用(Line HERE1 and HERE2) &(HERE3和;那么,两者的区别是什么呢?那么为什么要使用dynamic_cast
dynamic_cast
是"安全的",因为当你做一些"不好"的事情时,它会抛出异常或返回NULL(或者,正如Nawaz所说,它不会编译,因为类型足够糟糕,编译器可以看到它出错)
(Derived *)...
形式的行为与reinterpret_cast<Derived *>(...)
类似,这是"不安全的"-它将简单地将一个指针转换为另一个指针类型,无论是否产生有意义的结果。如果它表现得"不好",那是你的问题。
你可以这样做:
int x = 4711;
Derived *dp = (Derived *)x;
cout << dp->get_j();
编译器可能会抱怨整数的大小,但除此之外,它将编译代码。它很可能根本不会运行,但即使运行了,结果也可能没什么"有用的"。
相关文章:
- 如何理解C++标准N3337中的expr.const.cast子句8
- C++Cast运算符过载
- 在成员dynamic_bitset上使用 boost::from_block_range 时出错,但在本地dynamic
- C++类中的二维"dynamic"数组?
- 错误:"cast"未命名类型void setCastDescription(std::string
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- protobuf in C++ with dynamic binding for google::protobuf::M
- 警告的原因是什么:"when type is in parentheses, array cannot have dynamic size"?
- C++:"Expected '(' for function-style cast or type construction"错误
- 为什么选择 g++ 给予者:"error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]"
- CUDA 错误:"dynamic initialization is not supported for __device__, __constant__ and __shared__ variabl
- Gtk+ g_signal_connect() 和 C++ lambda 会导致"invalid cast"错误
- 如何修复'The procedure entry point SDL_RWclose could not be located in the dynamic link library'
- Shared_ptr cast vs static_cast speed
- 在 iOS 上使用 Aruco 构建 OpenCV 时"Functional-style cast from id to double is not allowed"
- "The ordinal 344 could not be located in the dynamic link library"
- 覆盖 CAST 运算符(我认为它被称为向下转换)
- Dynamic Cast C++ Fail
- dynamic-cast-c++dynamic_cast错误处理