class Product
{
...
}
class Perishable : public : Product
{
public:
int getday();
}
int main()
{
Product *temp;
//due to some coding
//temp could point to either Perishable object or Product object that is determine //during runtime
cout<< ((Perishable*)temp)->getday() ;// is there other way to achieve this typecasting seems dangerous
这段代码的问题在于,如果temp指向一个Product对象,那么temp->getday()是无效的。我不知道如何防止这种情况发生。如果由于某些原因,我只能在Perishable而不是Product中使用getday(),我该如何检查temp是指向一个易腐对象还是一个Product对象?
需要您的帮助,谢谢!