2015-09-05 131 views
1

這是我第一次嘗試使用類模板(我很新C++)如何解決此類模板錯誤?

我試圖創建一個非常簡單的Number類。首先,我要創建一個ToString方法。截至目前,爲了測試目的,我只想ToString返回字符串"testing"

當我運行我的代碼,我得到以下錯誤:

Undefined symbols for architecture x86_64: "Number<int>::ToString()", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [build/ml] Error 1

這裏是我的代碼,任何幫助表示讚賞:

的main.cpp

#include "number.h" 

int main(int argc, char* argv[]) { 
    Number<int> x(15); 
    x.ToString(); 
    return 0; 
} 

號.h

#ifndef _NUMBER_ 
#define _NUMBER_ 

#include <iostream> 

template <class T> 
class Number { 
    private: 
     T m_val; 
    public: 
     Number(T val) : m_val(val) {}; 
     std::string ToString(); 
}; 

#endif 

number.cpp

#include "number.h" 

template<class T> 
std::string Number<T>::ToString() { 
    return std::string("testing"); 
} 
+0

不同於一般的代碼,你必須把模板完全在頭文件。 (這是一個簡化,但最簡單的解決方案) –

+0

使'ToString'成爲一個const函數。你不需要用'std :: string'包圍引號 –

回答

1

嘗試包括在main.cppnumber.cpp(作爲臨時解決方法),而不是包括number.h。或者將ToString()的功能定義移動到number.h,並且只使用number.h

Why can templates only be implemented in the header file?

+0

你真的建議OP在另一個.cpp文件中包含一個.cpp文件嗎? http://stackoverflow.com/questions/1686204/why-should-i-not-include-cpp-files-and-instead-use-a-header – NathanOliver

+1

我最終只是將ToString的函數定義移動到number.h中 – David

相關問題