C++ 错误:";“对象”;未在此范围中声明

C++ 错误:";“对象”;未在此范围中声明,c++,codeblocks,C++,Codeblocks,有人能告诉我为什么会出现这个错误吗? 错误:firstpokemon未在此范围内声明。 还有其他的写作方法吗 #include <iostream> #include "Charmender.h" #include "Bulbasaur.h" #include "Game.h" #include "Squirtle.h" using namespace std; int main() { srand(time(0)); Game game; int frstchoice =

有人能告诉我为什么会出现这个错误吗? 错误:firstpokemon未在此范围内声明。 还有其他的写作方法吗

#include <iostream>
#include "Charmender.h"
#include "Bulbasaur.h"
#include "Game.h"
#include "Squirtle.h"

using namespace std;

int main()
{
 srand(time(0));
 Game game;
 int frstchoice = game.getstarterchoice();
    if(frstchoice == 1)
        Charmender firstpokemon;
    else if(frstchoice == 2)
        Bulbasaur firstpokemon;
    else if(frstchoice == 3)
        Squirtle firstpokemon;

cout << "You chose No." << frstchoice << endl;
cout << firstpokemon.getatk();
    return 0;
}
#包括
#包括“Charmender.h”
#包括“Bulbasaur.h”
#包括“Game.h”
#包括“Squirtle.h”
使用名称空间std;
int main()
{
srand(时间(0));
游戏;
int frstchoice=game.getstarterchoice();
如果(frstchoice==1)
查门德第一口袋妖怪;
else if(frstchoice==2)
第一口袋妖怪;
否则如果(frstchoice==3)
斯奎特尔第一口袋妖怪;

coutCode-inside如果语句在它们自己的作用域块中,那么它们仅在该块中是本地的


如果您的类继承自同一基类,则可以使用指向基类的指针,并在
If
语句中分配实例。

code-inside
If
语句位于其自己的作用域块中,因此它们仅在该块中是本地的


如果您的类继承自同一基类,则可以使用指向基类的指针,并在
If
语句中分配实例。

您有三个单独的变量,称为
firstpokemon
,每个变量的作用域位于声明它的
If…else
语句的分支内。它们是not在
main
的更大范围内

一个变量只能有一个类型。如果希望一个变量引用各种多态类型(假设有一个公共基类),则需要一个指针或引用,并且通常需要动态分配:

std::unique_ptr<Pokemon> firstpokemon;
if(frstchoice == 1)
    firstpokemon.reset(new Charmender);
else if(frstchoice == 2)
    firstpokemon.reset(new Bulbasaur);
else if(frstchoice == 3)
    firstpokemon.reset(new Squirtle);

if (firstpokemon)
    cout << firstpokemon->getatk();
else
    cout << "Wrong choice\n";
std::unique_ptr firstpokemon;
如果(frstchoice==1)
第一口袋妖怪。重置(新魔术师);
else if(frstchoice==2)
第一口袋妖怪。重置(新Bulbasaur);
否则如果(frstchoice==3)
第一口袋妖怪。重置(新喷射器);
如果(第一口袋妖怪)
coutgetatk();
其他的

您可以有三个单独的变量名为
firstpokemon
,每个变量的作用域都在声明它的
if…else
语句的分支内。它们不在
main
的更大范围内

一个变量只能有一个类型。如果希望一个变量引用各种多态类型(假设有一个公共基类),则需要一个指针或引用,并且通常需要动态分配:

std::unique_ptr<Pokemon> firstpokemon;
if(frstchoice == 1)
    firstpokemon.reset(new Charmender);
else if(frstchoice == 2)
    firstpokemon.reset(new Bulbasaur);
else if(frstchoice == 3)
    firstpokemon.reset(new Squirtle);

if (firstpokemon)
    cout << firstpokemon->getatk();
else
    cout << "Wrong choice\n";
std::unique_ptr firstpokemon;
如果(frstchoice==1)
第一口袋妖怪。重置(新魔术师);
else if(frstchoice==2)
第一口袋妖怪。重置(新Bulbasaur);
否则如果(frstchoice==3)
第一口袋妖怪。重置(新喷射器);
如果(第一口袋妖怪)
coutgetatk();
其他的

coutYour
firstpokemon
是一个局部变量,因为它是在
if
块中创建的。
作为局部变量,您不能在任何其他块中使用它,因此当您尝试
cout时,您的
firstpokemon
是一个局部变量,因为它是在
if
块中创建的。
作为一个局部变量,不能在任何其他块中使用它,因此当您试图
与当前问题相关时,但是如果
frstchoice
不是您检查的备选方案呢?与当前问题无关,但是如果
frstchoice
不是您检查的备选方案呢?