在c++中使用未声明的标识符

Use of undeclared identifier in c++

本文关键字:未声明 标识符 c++      更新时间:2023-10-16

我正在尝试创建一个滚动方法来移动我的背景精灵。但是当我在方法中引用背景精灵时,我得到了这个消息:

Use of undeclared identifier 'bg2'

这就是我在滚动方法中使用bg2的方法:

   void scroll() {
    Point pos2 = bg2.getPosition();
    pos1.x -= 5.0f;
    pos2.x -= 5.0f;
    if(pos1.x <=-(visibleSize.width*0.5f) )
    {
        pos1.x = pos2.x + winSize.width;
    }
    if(pos2.x <=-(winSize.width*0.5f) )
    {
        pos2.x = pos1.x + winSize.width;
    }
    background1.setPosition(pos1);
    background2.setPosition(pos2);

}

但是我在helloWorld.h中声明了bg2,像这样:

class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();  
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
//windows size
cocos2d::Size visibleSize;
cocos2d::Point origin;
//state machines
char gameState;
char playerState;
//sprites
cocos2d::Sprite* player;
cocos2d::Sprite* bg1;
cocos2d::Sprite* bg2;
cocos2d::Sprite* bg3;
cocos2d::Sprite* bg4;
cocos2d::Sprite* bg5;
cocos2d::Sprite* bg6;
cocos2d::Sprite* bg7;
cocos2d::Sprite* bg8;
cocos2d::Sprite* bg9;
cocos2d::Sprite* bg10;
cocos2d::Sprite* bg11;
bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event * event);
void onTouchMoved(cocos2d::Touch *touch, cocos2d::Event * event);
void onTouchEnded(cocos2d::Touch *touch, cocos2d::Event * event);
void scroll();

};

我还在helloWorld.cpp的init方法中定义了bg2

 //define background
bg1 = Sprite::create("005_chao_base.png");
bg1->setAnchorPoint(Point(0,0));
bg1->setPosition(Point(0, 0));
this->addChild(bg1,-1);
bg2 = Sprite::create("005_chao_base.png");
bg2->setAnchorPoint(Point(0,0));
bg1->setPosition(Point(bg1->getBoundingBox().size.width, 0));
this->addChild(bg2,-1);

我像这样在。cpp

中声明scroll方法
void scroll() {
}

和。h

void scroll();

cocos2d::Sprite是一个指针,注意*。所以应该是bg2->getPosition()

也,你在做cocos2d::Sprite* bg2;但使用:bg1 = Sprite::create("005_chao_base.png");

还有,要养成在所有东西的名字之间间隔的习惯。你自相矛盾。有时你用cocos2d::Sprite*,有时你不用cocos2d::

编辑:另外,你应该像。cpp
中的HelloWorld::Scroll一样命名空间滚动
  • void scroll()是类的成员函数。
  • 你在.cpp中声明另一个void scroll(),你想在它里面引用class HelloWorld的成员变量bg2,在这种情况下,你得到错误"未声明的标识符"。原因是非成员函数void scroll()不知道HelloWorld类的定义。所以你的问题是你错过了你的scroll函数的类标识符。
  • 解决方案是在.cpp中定义的void scroll()函数前面放置类标识符(例如,HelloWorld::scroll()),参见下面的代码:

void HelloWorld::scroll()
{
  Point pos2 = bg2->getPosition();
  ...
}
  • .h中删除正向声明void scroll();
  • 使用箭头操作符->bg2调用getPosition()bg2是指针。
  • 你应该没事。

如果编译器说你使用了未定义的符号,那么该符号不是用错误的类型定义的;

检查是否在.cpp模块源代码中包含了helloWorld.h