gpt4 book ai didi

C++基本多态性

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:47 24 4
gpt4 key购买 nike

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 中使用 getday() 而不能在 Product 中使用,我如何检查 temp 是指向易腐对象还是 Product 对象?

一些帮助将不胜感激/

最佳答案

“此代码的问题在于,如果 temp 指向 Product 对象,temp->getday() 将无效,我不知道如何防止这种情况发生。”

本着问题的精神,如果您绝对不想像其他答案中提到的那样在 Product 类中声明/实现 getday() ,则可以使用动态转换来确定变量的运行时类型,并且如果你有一个 Perishable 实例,那么只调用 getday() :

  Product* pPerishable = new Perishable;
Product* pProduct = new Product;
Perishable * pActualPerishable;

pActualPerishable= dynamic_cast<Perishable *>(pPerishable );
//pActualPerishable will not be null because it is of type Perishable at run time

pActualPerishable = dynamic_cast<Perishable*>(pProduct );
//pActualPerishable will be null because you are trying to cast a runtime base type to a derived type.

因此,尝试将您的变量动态转换为 Perishable,如果成功,您就知道可以调用 getday()。请注意,这不再是多态的,但在运行时确定类型有其用处,尤其是当您无法控制正在处理的对象的接口(interface)时。

关于C++基本多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9356520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com