我有一个C ++类main.cpp,我在其中创建了一个类如下:
class MapSearchNode
{
public:
unsigned int x; // the (x,y) positions of the node
unsigned int y;
MapSearchNode() { x = y = 0; }
MapSearchNode( unsigned int px, unsigned int py ) { x=px; y=py; }
float goalDistance( MapSearchNode &nodeGoal );
};
float MapSearchNode::goalDistance( MapSearchNode &nodeGoal )
{
float xd = fabs(float(((float)x - (float)nodeGoal.x)));
float yd = fabs(float(((float)y - (float)nodeGoal.y)));
return xd + yd;
}
int main{
//treatment
}
它工作正常,但后来我想分离MyClass类,所以我创建了一个MyClass.h和MyClass.cpp并将代码分开如下:
MyClass.h
#ifndef _MAPSEARCHNODE_H
#define _MAPSEARCHNODE_H
class MapSearchNode
{
public:
MapSearchNode();
MapSearchNode( unsigned int px, unsigned int py );
public:
unsigned int x;
unsigned int y;
float goalDistance( MapSearchNode &goalNode );
};
#endif
MyClass.cpp
#include "MapSearchNode.h"
MapSearchNode::MapSearchNode():x(0), y(0))
{}
MapSearchNode::MapSearchNode( unsigned int px, unsigned int py ):x(px), y(py)
{}
float MapSearchNode::goalDistance(MapSearchNode &goalNode ){
float xDistance = fabs(float(((float)x - (float)goalNode.x)));
float yDistance = fabs(float(((float)y - (float)goalNode.y)));
return xDistance + yDistance;
}
Bur我尝试编译时遇到错误:
Undefined identifier goalNode;
//for the function goalDistance
有人可以解释一下我为什么会收到此错误以及如何解决此问题。
编辑:我希望我现在没有忘记任何事情。编辑: 非常感谢那些沮丧的人。我们中的一些人不是像你这样的专家,他们很难看到错误甚至是小错误!
答案 0 :(得分:0)
首先看看有两个可能的原因导致此错误:
最明显的一个: 你的班级定义不完整,应该是
class MyClass
{
public:
unsigned int x;
unsigned int y;
MyClass() { x = y = 0; }
MyClass( unsigned int px, unsigned int py ) { x=px; y=py; }
float Calculate( MyClass &myClass );
}; // semicolon
float MyClass::Calculate( MyClass &myClass )
{
if(x<myClass.x)
....//treatment
}
此外,请确保您的源文件( .cpp)包含您的头文件( .h)
所以这两个文件看起来都是这样的:
// .h file
class MyClass
{
public:
unsigned int x;
unsigned int y;
MyClass() { x = y = 0; }
MyClass( unsigned int px, unsigned int py ) { x=px; y=py; }
float Calculate( MyClass &myClass );
};
// .cpp file
#include "MyClass.h"
//definition of constructors
float MyClass::Calculate( MyClass &myClass )
{
if(x<myClass.x)
....//treatment
}