因为CDerived和CIndepend没有继承关系,把dynamic_cast换成static_cast还是不行的,会出另外一个错: error C2440: 'static_cast' : cannot convert from 'class CDerived *' to 'class CIndepend *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast...
就经常而且也必须这样搞。CRTP 典型的把基类的 this 指针 static_cast 成子类指针,然后实现的零运行期...
class Base { virtual dummy() {} }; class Derived : public Base {}; Base* b1 = new Derived; Base* b2 = new Base; Derived* d1 = dynamic_cast<Derived *>(b1); // succeeds Derived* d2 = dynamic_cast<Derived *>(b2); // fails: returns 'NULL' 如果一个引用类型执行了类型转换并且...
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 在最后一行代码有问题,编译器给的错误提示,基类CBase不是vritual多态类型。 把类的定义改成: class CBase { virtual void dummy() {} }; class CDerived: public CBase...
class Base {}; class Derived : public Base {}; Base *a = new Base; Derived *b = static_cast<Derived *>(a); 'static_cast'除了操作类型指针,也能用于执行类型定义的显式的转换,以及基础类型之间的标准转换: 代码: double d = 3.14159265; ...
classBaseClass {public:intm_iNum; virtualvoid foo(){};//基类必须有虚函数。保持多台特性才能使用dynamic_cast};classDerivedClass:publicBaseClass {public:char*m_szName[100];voidbar(){}; }; BaseClass* pb =newDerivedClass(); DerivedClass*pd1 = static_cast<DerivedClass *>(pb);//子类->父类...
cast)有很大的区别,所以 C++ 引入了四种不同的具名转型(named cast)。从技术角度,C 风格转型不能...
class String { public: String ( const char* p ); // 用C风格的字符串p作为初始化值 //… } String s1 = “hello”; //OK 隐式转换,等价于String s1 = String(”hello”),将char型变成了string类 隐式转换二 使用operator what_you_want_to_convert_type() const ...
with: /cclassB{};classC:publicB { };classD:publicC { };voidf(D* pd){ C* pc =dynamic_cast<C*>(pd);// ok: C is a direct base class// pc points to C subobject of pdB* pb =dynamic_cast<B*>(pd);// ok: B is an indirect base class// pb points to B subobject of ...
(reference) to another classT2.T1andT2must be part of the same hierarchy, the classes must be accessible (via public derivation), and the conversion must not be ambiguous. In addition, unless the conversion is from a derived class to one of its base classes, the smallest part of the ...