簡體   English   中英

C ++繼承問題

[英]C++ inheritance problem

我正在嘗試使用堆作為基類來實現左派樹。 以下是heap.h的內容:

template <class T>

class heap {
public:
    virtual void init(T*) = 0;
    virtual void insert(T*) = 0;
    virtual T delete_min() = 0;
};

以下是leftist.cpp的內容:

#include "heap.h"

template <class T>
class leftist_tree : public heap<T> {
private:
    T* root;
public:
    void init(T* a) {}
    void insert(T* a) {}
    T delete_min() {T a; return a;}
};

我使用以下定義將另一個類leftist_node作為參數傳遞給該類:

leftist_tree<leftist_node> mytree;

我正在為函數init,insert和delete_min獲取LNK 2001未解析的外部符號錯誤。 我究竟做錯了什么?

編輯:

好吧,我在這一點上給出的例子太復雜了。 我試圖在較小的范圍內重現相同的錯誤,以便有人可以更容易地識別問題。 我創建了以下示例文件。

try.cpp

#include "stdafx.h"
#include "myclass.h"

int _tmain(int argc, _TCHAR* argv[])
{
    myclass<int> a;
    a.hello(3);
    return 0;
}

myclass.h

template <class T>

class myclass {
public:
    void hello(T);
};

myclass.cpp

#include "myclass.h"
#include <iostream>
using namespace std;

template <class T>
void myclass<T>::hello(T a){
    cout<<a<<endl;
    system("pause");
}

我收到類似的錯誤消息:

1> try.obj:錯誤LNK2001:未解析的外部符號“public:void __thiscall myclass :: hello(int)”(?hello @?$ myclass @ H @@ QAEXH @Z)1> c:\\ users \\ meher anand \\ documents \\ visual studio 2010 \\ Projects \\ try \\ Debug \\ try.exe:致命錯誤LNK1120:1個未解析的外部

你能告訴我我現在哪里出錯嗎? 謝謝

模板未針對該類型進行實例化。 最簡單的方法是從編譯中刪除.cpp,並將其包含在使用模板的cpp中。

另一個簡單的答案是在.h中定義整個模板。

模板函數的處理方式與常規函數略有不同。 在您嘗試使用它之前,編譯器實際上不會編譯該函數。 如果你嘗試使用它的唯一地方是.cpp,其中函數的主體是未定義的,它假定它必須在其他地方編譯並為鏈接器提供引用以便稍后填寫。

在你的情況下,你在leftist.cpp中定義了函數的主體,但你沒有在那里使用它,你在其他地方使用它。 如果你已經在.h文件中定義了它,那么在你嘗試使用它的任何地方都可以使用該定義,一切都會很好。 如果您已經在leftist.cpp中的某處使用過函數,那么函數就會被創建,鏈接器會修復所有內容。

一般規則是在頭文件中定義所有模板函數的主體。

每當你看到這個錯誤

錯誤LNK20XX未解析的外部符號

這意味着鏈接鏈接器時無法找到函數定義。 在你的情況下,這是錯誤的

希望這對你有所幫助。 如果您需要更多幫助,請與我們聯系

PK

以下應該工作(用g ++測試):

// File: heap.hh --------------------------
template <class T>
class heap {
public:a
    virtual void init(T*) = 0;
    virtual void insert(T*) = 0;
    virtual T delete_min() = 0;
};

// File: leftist_tree.hh ------------------
#include "heap.hh"
template <class T>
class leftist_tree : public heap<T> {
private:
    T* root;
public:
    void init(T* ) {}
    void insert(T* ) {}
    T delete_min() {T a; return a;}
};

// File: leftist_node.hh ------------------
struct leftist_node {
    int value;
};

// File: leftist_main.cpp -----------------
#include "leftist_tree.hh"
#include "leftist_node.hh"

int main() {
    leftist_tree< leftist_node > mytree;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM