我有以下 header helper.h:
#ifndef ADD_H
#define ADD_H
class Helper{
public:
static float calculateSpriteSize(float imgSize, float screenSize);
};
#endif
这是我的 helper.cpp:
#include "block.h"
#include "helper.h"
float Helper::calculateSpriteSize(float imgSize, float screenSize)
{
return ((imgSize/screenSize)*100);
}
但是,出于某种原因,当我通过执行以下操作在我的运行代码上调用我的函数 calculateSpriteSize 时:
#include "header.h"
int main(void){
float h = Helper::calculateSpriteSize( 168.0f, 170.0f );
)
我收到以下错误:
error: incomplete type 'Helper' used in nested name specifier
如有任何帮助,我们将不胜感激。
Block.h 如下所示:
#ifndef ADD_H
#define ADD_H
class Block{
private:
int imgID;
int life;
float price;
public:
Block();
void setImgID(int imgID);
int getImgID();
};
#endif
block.cpp 如下所示:
#include "block.h"
Block::Block()
{
}
void Block::setImgID(int imgID)
{
this->imgID = imgID;
}
int Block::getImgID()
{
return imgID;
}
更新:我按照 Rakete1111 的建议将 Helper 添加到类定义中。但这并没有解决问题。
更新 2:将前向声明更改为包含。添加了我的代码中的其他包含,以防它很重要。
最佳答案
前向声明引入的类型是incomplete type .但是调用成员函数需要类型完整,否则编译器怎么知道成员是否存在,以及成员的签名?
您需要包含头文件。
#include "helper.h"
int main(void){
float h = Helper::calculateSpriteSize( 168.0f, 170.0f );
)
编辑
您在“block.h”和“helper.h”中使用相同的宏 ADD_H
。这意味着
#include "block.h"
#include "helper.h"
第二次包含会失败,helper.h
的内容根本不会被包含。
将包含的守卫宏名称改为唯一的,最好与文件名的名称一致。比如HELPER_H
和BLOCK_H
。
关于C++ 错误 : incomplete type used in nested name specifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38841420/