[英]Why am I having trouble compiling a templated class?
我在這段代碼上停留了一段時間,無法編譯,我到底在做什么錯? 如果在編譯時存在錯誤,請忽略它們,因為我可以自己解決此問題。 截至目前,我只是試圖使其運行。 先感謝您。
#include <iostream>
#include <string.h>
//template <class t> class Matrix; //possible way of fixing the friend function.
using namespace std;
template<class T, size_t NROWS, size_t NCOLS>
std::ostream & operator<<(std::ostream &os, const Matrix<T,NROWS, NCOLS> &matrix);
template<class T, size_t NROWS = 1, size_t NCOLS = 1>
class Matrix{
public:
Matrix(){}
friend std::ostream &operator<< <>(std::ostream&os,const Matrix<T, NROWS, NCOLS> &matrix);
private:
T container[NROWS][NCOLS];
};
template<class T,size_t NROWS, size_t NCOLS>
std::ostream &operator<<(std::ostream &os,const Matrix<T,NROWS,NCOLS>&matrix){
for(size_t i=0;i<NROWS;++i){
for(size_t j=0;j<NCOLS;++j){
os <<matrix.container[i][j]<<" ";
}
os <<std::endl;
}
os <<std::endl;
}
int main(){
Matrix<float, 10, 5> mat;
cout << mat;
return 0;
}
我使用的IDE中的錯誤如下:
main.cpp:8:51:錯誤:沒有名為'Matrix'的模板std :: ostream&operator <<(std :: ostream&os,const Matrix&matrix);
main.cpp:15:24:錯誤:沒有功能模板與功能模板專業化匹配'operator <<'朋友std :: ostream&operator << <>(std :: ostream&os,const Matrix&matrix);
main.cpp:35:32:注意:在實例化模板類'Matrix'時,此處要求矩陣矩陣;
如果取消注釋第4行,並按如下所示對其進行更改,則將編譯您的代碼:
template <class t, size_t, size_t> class Matrix; //possible way of fixing the friend function.
看來您的問題是,前向聲明的Matrix模板參數與以后出現的Matrix定義不匹配。
同樣,盡管代碼將在此修復后編譯,但是仍然可能會出現警告,您可能還需要修復:
In function 'std::ostream& operator<<(std::ostream&, const Matrix<T, NROWS, NCOLS>&)':
31:1: warning: no return statement in function returning non-void [-Wreturn-type]
#include <cstddef>
#include <iostream>
template<typename, std::size_t, std::size_t> class Matrix;
template<typename T, std::size_t NROWS, std::size_t NCOLS>
std::ostream& operator<<(std::ostream &os, Matrix<T, NROWS, NCOLS> const &matrix)
{
for (std::size_t row{}; row < NROWS; ++row, os.put('\n'))
for (std::size_t col{}; col < NCOLS; ++col)
os << matrix.container[row][col] << ' ';
return os.put('\n');
}
template<typename T, std::size_t NROWS = 1, std::size_t NCOLS = 1>
class Matrix {
T container[NROWS][NCOLS] = {};
friend std::ostream& operator<< <>(std::ostream&, Matrix<T, NROWS, NCOLS> const&);
};
int main()
{
Matrix<float, 10, 5> mat;
std::cout << mat;
}
請擺脫C標頭<string.h>
。
您需要先定義矩陣,然后才能使用它:
template<class T, size_t NROWS = 1, size_t NCOLS = 1>
class Matrix;
並添加一個return語句操作<<,返回操作系統。 您也不需要重復operator <<聲明,您只能在類主體中聲明它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.