C++ 在C++;错误
我想在Application.cpp中使用Stats.cpp中的一个函数。以下是我的代码片段: 在Stats.h中:C++ 在C++;错误,c++,C++,我想在Application.cpp中使用Stats.cpp中的一个函数。以下是我的代码片段: 在Stats.h中: #ifndef STATS_H #define STATS_H class Stats { public: void generateStat(int i); }; #endif 在Stats.cpp中: #include Stats.h void generateStat(int i) { //some process code here } 在Appl
#ifndef STATS_H
#define STATS_H
class Stats
{
public:
void generateStat(int i);
};
#endif
在Stats.cpp中:
#include Stats.h
void generateStat(int i)
{
//some process code here
}
在Application.cpp中:
int main()
{
generateStat(10);
}
我得到了一个“未解析的外部符号”错误,但是我不知道为了Application.cpp还需要包括什么。有什么想法吗?
generateStat
是您的Stats
课程的一部分。您需要实例化一个Stats
对象(以及main
类中Stats.h
的必要包含项)
比如说,
Stats stat;
stat.generateStat(i);
此外,函数定义需要在Stats.cpp中包含类名
Stats::generateStat
您需要定义generateStat
,如下所示:
#include Stats.h
void Stats:: generateStat(int i) // Notice the syntax, use of :: operator
{
//some process code here
}
然后创建类的对象Stats
,使用它调用公共成员函数generateStat
Stats s;
s.generateStat( 10 ) ;
使用以下内容构建应用程序:
g++-o stats stats.cpp Application.cpp-I.
两周前(工作时)发生了相同的错误消息
乍一看——试试:
缺少类名。因此,未解决
顺便说一句,关于你的头——另一个问题,这个#ifndef指令不应该是必需的,因为你应该在一个名称空间中只声明一次Stats
#ifndef CLASS_H
#define CLASS_H
#include "Class.h"
#endif
这是一个通用示例-可在cpp文件中使用
编辑:现在,我看到了您的调用(您案例中的主要方法)。您需要一个对象实例来调用您的方法
Stats* stats = new Stats(); //add a default constructor if not done
stats->generateStat(77);
// any other stats stuff ......
// in posterior to the last use
delete(stats);
在标题中:
Stats::Stats(){}; //with an empty body - no need to write it again in the cpp file
这很有趣。。。调用
generateStat(10)
似乎被编译器接受,没有任何声明。这是C++吗?你有一些问题,最好检查一下。@ Cordah你在说什么?首先,代码> STATS STATS/<代码>应该是代码> STATS*STATS。然后您必须将stats.generateStat
更改为stats->generateStat
。为什么不直接在堆栈上创建它呢?而且你没有删除它(如果你要提倡在堆上创建的话,不妨表明这一点)。@codah+1&&yes,没有关注这一点
Stats::Stats(){}; //with an empty body - no need to write it again in the cpp file