gpt4 book ai didi

c++ - 如何在 if 语句之外访问在 if 语句内创建的指针?

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:13 26 4
gpt4 key购买 nike

我正在制作一个简单的程序来根据用户选择的神奇宝贝播放特定的战斗调用。我有一个主类(Pokemon 类)和两个从主类继承虚拟 battleRoar() 函数的类。这是代码

#include <iostream>
using namespace std;

class Pokemon{
public:
virtual void battleCall(){
}
virtual ~Pokemon() {}
};

class Weedle: public Pokemon{
public:
Weedle(){
cout << "Weedle Weedle!" << endl;
}
void battleCall(){
cout << "-v- weedle" << endl;
}
};

class Pikachu: public Pokemon{
public:
Pikachu(){
cout << "Pikaaaachu!" << endl;
}
void battleCall(){
cout << "pikachu!!" << endl;
}

};


int main(){

cout << "Please pick a pokemon." << endl;
cout << "1. Weedle" << endl;
cout << "2. Pikachu" << endl;
int a;
cin >> a;
if (a == 1){
cout << "You picked a weedle!" << endl;
Weedle chosenPoke;
Pokemon *p1 = &chosenPoke;

}
else if (a == 2){
cout << "You picked a pikachu!" << endl;
Pikachu chosenPoke;
Pokemon *p1 = &chosenPoke;
} else { cout << "Invalid choice" << endl;}
cout << "Would you like to hear your pokemon's battle call?" << endl;
cout << "Yes or No" << endl;
string choose;
cin >> choose;
p1->battleCall(); //produces error: use of undeclared identifier 'p1




return 0;
}

我遇到的问题是指向子类的主类指针在条件之外不再可访问。在这种情况下,我知道在条件语句的每个分支中调用 roar 会很简单。但是,我希望能够调用使用指针创建的任何子类,而不是为条件的每个变体创建调用函数。

最佳答案

if block 之前声明指针并更改要返回的对象的创建。

Pokemon *p1;
if (a == 1){
cout << "You picked a weedle!" << endl;
/* Weedle chosenPoke; -- don't construct the object on the stack */
p1 = new Weedle();
}
...
p1->battleCall();
delete p1;
...

这解决了未声明标识符的直接问题,但增加了您必须在不再需要时删除该对象的负担 - 或者更改您的代码以使用智能指针。

关于c++ - 如何在 if 语句之外访问在 if 语句内创建的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083448/

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