gpt4 book ai didi

C++ 在 if-else 内部声明派生类对象并在外部使用它

转载 作者:行者123 更新时间:2023-11-30 05:29:58 26 4
gpt4 key购买 nike

我有一个名为 Alma 的(父)类,带有(虚拟)函数 Getwidth()Alma 的两个派生类,名为Birs(具有特殊函数Getheight())和Citrom(具有特殊函数Getdepth())。我想声明一个对象 - 名为 Attila - 类型是 BirsCitrom 取决于 bool。稍后,我想使用常用函数 Getwidth() 以及特殊函数(取决于提到的 bool)。

我的(不工作)代码:

/*...*/
/*Classes*/
class Alma{
public: virtual int Getwidth() = 0;
/*ect...*/
}

class Birs: public Alma{
int Getwidth(){return 1;}
public: int Getheight(){return 2;}
/*ect...*/
}

class Citrom: public Alma{
int Getwidth(){return 3;}
public: int Getdepth(){return 4;}
/*ect...*/
}
/*...*/
/*Using them*/
void Useobjects(){

/*Create object depending on bool*/
if(b00lvar){
Birs Andor();
std::cout<<Andor.Getwidth()<<" "<<Andor.Getheight()<<std::endl;
}else{
Citrom Andor();
std::cout<<Andor.Getwidth()<<" "<<Andor.Getdepth()<<std::endl;
}

/*Using the common part of object*/
std::cout<<Andor.Getwidth()<<std::endl;

/*Using the special part of object*/
if(b00lvar){
std::cout<<Andor.Getheight()<<std::endl;
}else{
std::cout<<Andor.Getdepth()<<std::endl;
}

/*ect...*/
}

最佳答案

这是多态对象处理的经典案例。只需确保您熟悉该概念以及指针和引用即可。

你需要的是这样的东西:

Alma* Andor;

if(b00lvar){
Andor = new Birs();
std::cout<<Andor->Getwidth()<<" "<<Andor->Getheight()<<std::endl;
}else{
Andor = new Citrom();
std::cout<<Andor->Getwidth()<<" "<<Andor->Getdepth()<<std::endl;
}

接下来使用dynamic_cast 返回派生类型,最后当然不要忘记删除对象。但首先要了解这些概念。

关于C++ 在 if-else 内部声明派生类对象并在外部使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36218655/

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