Why does this return false and how can I fix it? I'm trying to make a program that writes data to a file and can read that file back in and display it. Also, there are 3 classes. One is a parent class (MyEmployee not displayed) and the Hourly and Salaried classes are child classes.
for (int i = 0; i < ARRAY_SIZE; i++)
{
MyEmployee* empPtr = payroll[i];
if (typeid(*empPtr) == typeid(Hourly))
{
Hourly* empHPtr = static_cast<Hourly*>(empPtr);
}
else if (typeid(*empPtr) == typeid(Salaried))
{
Salaried* empSPtr = static_cast<Salaried*>(empPtr);
}
}
for (int i = 0; i < ARRAY_SIZE; i++)
{
payroll[i]->writeData(myWrittenFile);
}
If MyEmployee
is polymorphic use dynamic_cast < type-id > ( expression )
This Converts the operand expression to an object of type type-id and will return 0 if the conversion fails.
MyEmployee* empPtr = payroll[i];
if (dynamic_cast<Hourly*>(empPtr))
{
...
}
I'm going to guess that your class hierarchy is:
struct MyEmployee { virtual ~MyEmployee() {}; /* ... */ };
struct Hourly : MyEmployee { /* ... */ };
struct Salaried : MyEmployee { /* ... */ };
If so, then you could replace your code with:
MyEmployee *empPtr = payroll[i];
Hourly *empH = dynamic_cast<Hourly *>(empPtr);
Salaried *empS = dynamic_cast<Salaried *>(empPtr);
The empH
and empS
will be null if the object was not of that type; and a valid pointer if it was of that type.
Of course, it may be better to replace this whole thing with a virtual function, as chris suggested.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.