在 .h 中声明名称,但在 Xcode 中以.cpp形式报告未声明

declared name in.h but reports undeclare in .cpp in Xcode

本文关键字:cpp 中以 未声明 报告 Xcode 但在 声明      更新时间:2023-10-16

下面是我的代码:

MathCore.h

#ifndef __CC_MATHCORE_H__
#define __CC_MATHCORE_H__
#include "math.h"
class MathCore
{
public:
    MathCore();
    virtual ~MathCore( );
    int x (int n  );
};
#endif

数学核心.cpp

#ifndef __CC_MATHCORE_H__
#define __CC_MATHCORE_H__
#include "MathCore.h"
MathCore::MathCore()//a
{
}
MathCore::~ MathCore()//b
{
}
int MathCore::x (int n  )//c
{
    float v=0;
    return v;
}
#endif 

但它错误在

a:C++ requires a type specifier for all declarations
  Use of undeclared identifier 'MathCore'
b:Expected a class or namespace
c:Expected a class or namespace

欢迎您的评论

.cpp 和 .h 文件中都不应该有该#define,因为它会阻止实际包含 .h 文件的内容。

当您#include文件时,出于所有实际目的,它的行为方式与将该文件复制并粘贴到您拥有#include的任何位置相同。所以,你的MathCore的前几行.cpp实际上是这样的:

#ifndef __CC_MATHCORE_H__
#define __CC_MATHCORE_H__
#ifndef __CC_MATHCORE_H__
#define __CC_MATHCORE_H__
/* the rest of your .h file here */

当以这种方式重组时,它会变得更加明显,第二个#ifndef永远无法匹配,因为它正在检查的交易品种是在上面定义的。

因为,在C++文件中,您使用的标头保护与标头相同。第二行定义__CC_MATHCORE_H__ 。在此之后,您将包含标头,如果定义了__CC_MATHCORE_H__不会执行任何操作。从 cpp 文件中删除防护装置,你会没事的。在实际实现文件中很少需要防护(如果有的话)。

//////////////////////////////////MathCore.cpp 
#include "MathCore.h"
MathCore::MathCore()//a
{
}
MathCore::~ MathCore()//b
{
}
int MathCore::x (int n  )//c
{
    float v=0;
    return v;
}

从 MathCore 中删除包含保护.cpp