![](/img/trans.png)
[英]Problem with separating a class into header (.h) and source (.cpp) file
[英]Problem separating .h and .cpp file
我正在编写一个类,需要将声明与实现分开,但是在编译和链接测试程序时,我始终收到“未定义的引用”错误。 当我将实现包含在.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文件添加了存根
听起来像是链接问题。 这意味着您必须首先编译您的类-这将创建一个编译的目标文件。 然后在传递该类的已编译版本的同时编译主程序。
像这样:
g++ -c huge_integer.cpp
g++ main.cpp huge_integer.o
如果不同,请用mingw命令替换g ++。
与链接无关,但是您是在类声明本身中引用Huge_Integer
。
至少对于g ++,应该在前面添加一个前向声明,以便Huge_Integer
在类声明中具有含义,因此:
class Huge_Integer; // forward declaration
class Huge_Integer {
Huge_Integer();
// etc...
void add(Huge_Integer);
注意:我没有评论权限,因此必须在答案框中输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.