c ++模板构造函数的问题

gma*_*man 4 c++ templates 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

请帮我理清故障.

Joh*_*nck 5

由于您已经创建了自己的构造函数,因此未提供编译器生成的默认构造函数.因此,当您创建P2没有其构造函数的参数时,您需要为其编译默认构造函数.