C++ 指向基,转换为派生指针
是否可以使用C++ 指向基,转换为派生指针,c++,oop,pointers,casting,C++,Oop,Pointers,Casting,是否可以使用typeid(type).name()获取基的派生类的类型名 静态地将基指针推回派生指针的示例 #include <iostream> #include <typeinfo> class base { public: virtual void known() = 0; }; class derived: public base { public: void known() { std::cout << " I guess th
typeid(type).name()
获取基的派生类的类型名
静态地将基指针推回派生指针的示例
#include <iostream>
#include <typeinfo>
class base
{
public:
virtual void known() = 0;
};
class derived: public base
{
public:
void known() { std::cout << " I guess this means "; }
void unknown(){ known(); std::cout << " its possible "; }
};
int main()
{
derived d;
std::cout << typeid( d ).name() << std::endl;
// Prints out being a pointer to a derived class
base* b = &d;
std::cout << typeid( b ).name() << std::endl;
// Prints out being a pointer to a base class
// But how would you use it, or in any other way,
//get the original derived type name
derived * db = (derived*) b;
// db is casted at at compile time, the derived class is known
db->unknown();
}
#包括
#包括
阶级基础
{
公众:
虚空已知()=0;
};
派生类:公共基
{
公众:
void known(){std::cout给定类型为多态基类的表达式,typeid
运算符的结果引用表示最派生对象类型的std::type_info
对象
示例:
#include <iostream>
#include <typeinfo>
class Base {
public:
virtual ~Base() {}
}; // Base
class Derived : public Base {};
int main() {
Derived derived;
/* By reference. */ {
Base &base = derived;
std::cout << typeid(base).name() << std::endl;
}
/* By pointer. */ {
Base *base = &derived;
std::cout << typeid(*base).name() << std::endl;
// NOTE: typeid(base).name() results in printing of the Base class' name.
}
}
#包括
#包括
阶级基础{
公众:
虚拟~Base(){}
};//基础
派生类:公共基{};
int main(){
派生的;
/*通过引用。*/{
基&基=派生;
std::cout不做dynamic\u cast
不做你想做的事吗?不,这要求我确切地知道派生类是什么。或者我是这么读到的。我认为你想要的是@mpark不完全是。这要求它被手动写下来,这意味着在编译之前必须知道这些类。我认为第二个print语句应该是bestd::cout