我正在编写一个类,需要将声明与实现分开,但在编译和链接我的测试程序时,我一直收到“未定义的引用”错误。当我将实现包含在.h文件中时它工作正常,所以我相信我在那里做错了。我只是无法弄清楚是什么。
Huge_Integer.h
#ifndef HUGE_INTEGER_H
#define HUGE_INTEGER_H
#include <vector>
#include <string>
using namespace std;
class Huge_Integer
{
public:
Huge_Integer();
Huge_Integer(string);
void input();
string output();
void add(Huge_Integer);
void subtract(Huge_Integer);
bool is_equal_to(Huge_Integer);
bool is_not_equal_to(Huge_Integer);
bool is_greater_than(Huge_Integer);
bool is_less_than(Huge_Integer);
bool is_greater_than_or_equal_to(Huge_Integer);
bool is_less_than_or_equal_to(Huge_Integer);
private:
vector<int> value;
};
#endif
Huge_Integer.cpp
#include<vector>
#include<string>
#include<iostream>
#include "Huge_Integer.h"
using namespace std;
// all stubs for now...
Huge_Integer::Huge_Integer()
{
cout << "object created\n";
}
Huge_Integer::Huge_Integer(string s)
{
cout << "object created\n";
}
//etc...
如果我将#include "Huge_Integer.cpp"
放在我的测试文件中,它也有效,但我不应该这样做,对吗?
我正在使用MinGW。
提前致谢!
编辑:从我的.cpp文件中添加了存根
答案 0 :(得分:2)
听起来像一个链接问题。 这意味着你必须首先编译你的类 - 这将创建一个编译的目标文件。 然后在传递该类的编译版本时编译主程序。
像这样:
g++ -c huge_integer.cpp
g++ main.cpp huge_integer.o
如果不同,请用mingw命令替换g ++。
答案 1 :(得分:-1)
与链接无关,但您在类声明本身中指的是Huge_Integer
。
至少使用g ++,你应该先添加一个前向声明,以便Huge_Integer
在类声明中有意义:
class Huge_Integer; // forward declaration
class Huge_Integer {
Huge_Integer();
// etc...
void add(Huge_Integer);
注意:我没有评论权限,因此我必须输入答案框。