我已经翻阅了很多类似的帖子,关于这种问题,但我仍然无法解决这个错误。任何帮助将被感激。
/*samp.h header file*/
#include<iostream>
using namespace std;
class test
{
private:
test();
public:
static void const_caller();
};
/*samp.cpp file*/
#include<iostream>
using namespace std;
class test
{
private:
test()
{
cout<<"priv cont called\n";
}
public:
static void const_caller()
{
cout<<"calling priv const\n";
}
};
/*main.cpp file */
#include"samp.h"
using namespace std;
int main(int argc, char **argv)
{
test::const_caller();
}
当我做
g++ samp.cpp main.cpp -o main.out
我得到这个错误
/usr/bin/ld: /tmp/ccHZVIBK.o: in function `main':
main.cpp:(.text+0x14): undefined reference to `test::const_caller()'
我无法解决这个问题,因为我已经很久没有解决了。
在 samp.cpp
文件中再次定义测试类。
你需要在文件中加入 samp.h
头,并实现以下方法 test
类的定义。
#include "samp.h"
using namespace std;
test::test()
{
cout << "priv cont called\n";
}
void test::const_caller()
{
cout << "calling priv const\n";
}
在你发布的代码中,.cpp文件包含了它自己的类的定义,它与.h文件中的类名称相同,但实际上是一个不同的类。
在.cpp文件中,你需要使用:
test::test()
{
cout<<"priv cont called\n";
}
void test::const_caller()
{
cout<<"calling priv const\n";
}