MSDN中也提到了,实际中可将reinterpret_cast应用到哈希函数中,如下(64位系统中需将unsigned int修改为unsigned long): //expre_reinterpret_cast_Operator.cpp//compile with: /EHsc#include <iostream>//Returns a hash code based on an addressunsignedshortHash(void*p ) { unsignedintval = reinterpret_cast<u...
};classProgrammer :publicEmployee {public:intsalary();intbonus();//直接在这里扩展};//somewhere.cppintProgrammer::bonus() {//define} classMyCompany {public:voidpayroll(Employee *pe);//};voidMyCompany::payroll(Employee *pe) { Programmer*pm = dynamic_cast<Programmer *>(pe);//如果pe实际指向...
代码语言:cpp 复制 #include<iostream> class Base { public: virtual ~Base() {} virtual void print() { std::cout << "Base\n"; } }; class Derived : public Base { public: void print() override { std::cout << "Derived\n"; } }; int main() { Base* base = new Derived(); if...
// TestCast.cpp : Defines the entry point for the console application. // #include " stdafx.h " #include <iostream> using namespace std; class Base { public: virtual void f() { cout << "Base::f" << endl; } void f1(){cout << "Base::f1" << endl;} private: double x; dou...
cpp class Base { public:virtual ~Base() {} // 必须要有虚析构函数以支持多态 };class Derived...
//Emplyee.cpp intProgrammer::bonus() { // } payroll()通过多态来调用bonus() classMyCompany { public: voidpayroll(Employee*pe); // }; voidMyCompany::payroll(Employee*pe) { //do something //pe->bonus(); } 但是现在情况是,我们并不能修改源代码,怎么办?dynamic_cast华丽登场了!
1)如果表达式 的类型刚好是目标类型 或目标类型 的更少 cv 限定版本,那么结果是表达式 具有目标类型 类型的值。也就是说,dynamic_cast可以用来添加常量性。隐式转换和static_cast也能进行此转换。 2)如果目标类型 是“到(可有 cv 限定的)Base的指针”、表达式 的类型...
其中类型A为基类,类型B<1>继承自A,类型B<N>继承自B<N-1>,测试时使用类型A的指针指向一个B<N>或C<N>的实例,测试将该指针转换成B<0> *的效率。编译器为g++13,编译选项使用g++ a.cpp -std=c++20 -O2。结果如下 从结果中可以看出 static_cast转换的效率不受继承深度的影响...
// testCast.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <vector> usingnamespacestd; classCAnimal { public: virtualvoideat() { cout<<"animal eat"<<endl; } }; classCDog:publicCAnimal
cpp #include <iostream> #include <exception> class Base { public: virtual ~Base() {} // 必须有虚函数才能使用dynamic_cast }; class Derived1 : public Base { public: void show() { std::cout << "Derived1" << std::endl; } }; class Derived2 : public ...