dynamic_castingに少し問題があります。実行時にオブジェクトのタイプを判別する必要があります。これがデモです:
#include <iostream>
#include <string>
class PersonClass
{
public:
std::string Name;
virtual void test(){}; //it is annoying that this has to be here...
};
class LawyerClass : public PersonClass
{
public:
void GoToCourt(){};
};
class DoctorClass : public PersonClass
{
public:
void GoToSurgery(){};
};
int main(int argc, char *argv[])
{
PersonClass* person = new PersonClass;
if(true)
{
person = dynamic_cast<LawyerClass*>(person);
}
else
{
person = dynamic_cast<DoctorClass*>(person);
}
person->GoToCourt();
return 0;
}
上記をやりたいと思います。私がそれを行うために見つけた唯一の合法的な方法は、事前にすべてのオブジェクトを定義することです。
PersonClass* person = new PersonClass;
LawyerClass* lawyer;
DoctorClass* doctor;
if(true)
{
lawyer = dynamic_cast<LawyerClass*>(person);
}
else
{
doctor = dynamic_cast<DoctorClass*>(person);
}
if(true)
{
lawyer->GoToCourt();
}
これに関する主な問題は(使用されないオブジェクトの束を定義する必要があることを除いて)、「person」変数の名前を変更する必要があることです。もっと良い方法はありますか?
(クラス(Person、Lawyer、またはDoctor)は、私のコードを使用する人々が持っているライブラリの一部であり、変更したくないため、変更することはできません)。
ありがとう、
デイブ