isinstance函数对应的c++
时间: 2023-06-16 18:05:42 浏览: 73
在 C++ 中,可以使用 dynamic_cast 来实现类似于 Python 中 isinstance 的功能。dynamic_cast 可以将一个指向基类的指针或引用转换为指向派生类的指针或引用,如果转换成功则返回指向派生类的指针或引用,否则返回 nullptr。例如:
```c++
#include <iostream>
class Base {
public:
virtual void foo() {
std::cout << "Base::foo" << std::endl;
}
};
class Derived : public Base {
public:
void foo() override {
std::cout << "Derived::foo" << std::endl;
}
};
int main() {
Base* b = new Derived();
if (auto d = dynamic_cast<Derived*>(b)) {
d->foo(); // 输出 Derived::foo
} else {
std::cout << "Not a Derived object" << std::endl;
}
delete b;
return 0;
}
```
在上面的例子中,我们首先定义了一个基类 Base 和一个派生类 Derived,然后在 main 函数中创建了一个 Derived 对象,并将它的地址赋给一个指向 Base 的指针 b。然后通过 dynamic_cast 将 b 转换为指向 Derived 的指针 d,如果转换成功则调用 d->foo() 输出 "Derived::foo",否则输出 "Not a Derived object"。最后记得释放动态分配的内存。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)