我将 CCTouchTargetedDelegate 与 CCSprite 的子类一起使用。 在定义委托(delegate)方法时,我无法在函数内部使用“this”。
如对先前问题的回答 我不能将类名与使用范围解析的函数一起使用,因为它随后给了我错误 “‘ccTouchBegan’的外联定义与‘mygames::DragSprite’中的任何声明都不匹配”
我也尝试在 .h 文件中声明该函数,但似乎没有任何效果。
我的代码如下:-
.h文件
#pragma once
#include "cocos2d.h"
namespace mygames
{
class DragSprite: public cocos2d::CCSprite, public cocos2d::CCTargetedTouchDelegate
{
public:
DragSprite* createWithFile(const char *pszFileName);
bool isTouchingOnSprite(cocos2d::CCPoint touch);
virtual bool init();
bool ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent);
static inline cocos2d::CCPoint ccpSub(const cocos2d::CCPoint v1, const cocos2d::CCPoint v2);
private:
bool isDrag;
cocos2d::CCPoint whereTouch;
};
}
.cpp 文件
#include "DragSprite.h"
using namespace mygames;
bool DragSprite::init()
{
if (!CCSprite::init()) {
return false;
}
whereTouch = cocos2d::CCPointZero;
isDrag = false;
return true;
}
DragSprite* DragSprite::createWithFile(const char *pszFileName)
{
DragSprite *pSprite = new DragSprite();
if (pSprite&&pSprite->initWithFile(pszFileName))
{
cocos2d::CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(pSprite, 0, true);
pSprite->autorelease();
return pSprite;
}
CC_SAFE_DELETE(pSprite);
return NULL;
}
bool DragSprite::isTouchingOnSprite(cocos2d::CCPoint touch)
{
if (this->boundingBox().containsPoint(touch)) {
return true;
}else
{
return false;
}
}
static inline cocos2d::CCPoint ccpSub(const cocos2d::CCPoint v1, const cocos2d::CCPoint v2)
{
return ccp(v1.x-v2.x, v1.y-v2.y);
}
//CCTargetedTouchDelegate
bool ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
cocos2d::CCPoint touchPoint = pTouch->getLocation();
if (this->isTouchingOnSprite(touchPoint)) {
this->whereTouch = ccpSub(this->position, touchPoint);
return true;
}
return false;
}
错误屏幕截图:-
我在这里错过了什么?
只是出于好奇
按照答案中的建议,如果我使用
bool DragSprite::ccTouchBegan
那么,它还会调用 delegete 函数吗?或者只是我的 DragSprite 类中的函数。我的意思是,该功能仍会被覆盖吗? 出色地... 它是在 CCTargetedTouchDelegete 中声明的方法。我猜它是一个抽象函数。
最佳答案
bool ccTouchBegan(
需要
bool DragSprite::ccTouchBegan(
首先你不应该需要this
。
关于c++ - 在非静态成员函数错误之外无效使用 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23466080/