[英]Problem with c++ template constructor
碼:
#include<iostream>
using namespace std;
template<class T, int N> class point {
T coordinate[N];
public:
point(const point<T,N>&);
const double& operator[](int i) const {
return coordinate[i];
}
};
template<class T, int N> point<T,N>::point(const point<T,N>&p)
{
for(int i=0;i<N;i++)
coordinate[i]=p.coordinate[i];
};
int main() {
point<int,2> P2;
point<double,3> P3;
cout<<P2[0]<<P3[1];
return 0;
}
輸出:
prog.cpp: In function ‘int main()’:
prog.cpp:17: error: no matching function for call to ‘point<int, 2>::point()’
prog.cpp:11: note: candidates are: point<T, N>::point(const point<T, N>&) [with T =
int, int N = 2]
prog.cpp:18: error: no matching function for call to ‘point<double, 3>::point()’
prog.cpp:11: note: candidates are: point<T, N>::point(const point<T, N>&) [with T =
double, int N = 3]
prog.cpp: In member function ‘const double& point<T, N>::operator[](int) const [with
T = int, int N = 2]’:
prog.cpp:19: instantiated from here
prog.cpp:8: warning: returning reference to temporary
請幫我理清故障。
由於您已經創建了自己的構造函數,因此未提供編譯器生成的默認構造函數。 因此,當您創建不帶構造函數參數的P2
時,您需要為其編譯默認構造函數。
當你聲明一個類似的變量時,
point<int,2> P2;
它使用默認構造函數; 它可以在兩種情況下使用:
從這里你什么都不做:只聲明一個空的默認構造函數:
template<class T, int N> class point {
//...
public:
point() {} // <-- default constructor
};
這將清除您的錯誤。
還有一個重要警告 :
prog.cpp:8: warning: returning reference to temporary
那是因為你的operator []
。 改變線,
const double& operator[](int i) const
至,
const T& operator[](int i) const // for <int, N> you should return 'int' not 'double'
問題在於這兩條線
point<int,2> P2;
point<double,3> P3;
您正嘗試通過默認的無參數構造函數創建兩個“點”對象。
但是,除非您未指定任何其他構造函數,否則不會自動生成此構造函數。 實現默認構造函數將解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.