![](/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.