Find out Type of C++ Void Pointer(找出 C++ 空指针的类型)
问题描述
我有一个小问题:如何找出 C++ 指针的类型?
I have a small question: how do I find out what type a C++ pointer is?
我经常在我的控制台程序中使用一个小函数来收集输入,它看起来像这样:
I often use a small function in my console programs to gather input, which looks something like this:
void query(string what-to-ask, [insert datatype here] * input)
我想创建一个通用表单,使用一个空指针,但我不能创建一个空指针,那么我如何找出它的类型以便我可以转换它?
I would like to create a generic form, using a void pointer, but I can't cin a void pointer, so how to I find out it's type so I can cast it?
推荐答案
你不能.
然而,一种替代方法是取消空指针,让所有东西都派生自一个公共基类并使用 RTTI.
However, one alternative is to do away with void pointers, make everything derive from a common base class and use RTTI.
示例:
class Base
{
public:
virtual ~Base() {}
};
class Foo : public Base { /* ... */ };
void SomeFunction(Base *obj)
{
Foo *p = dynamic_cast<Foo*>(obj);
if (p)
{
// This is of type Foo, do something with it...
}
}
这篇关于找出 C++ 空指针的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:找出 C++ 空指针的类型
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
