gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:39:47 25 4
gpt4 key购买 nike

代码:

#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 且其构造函数没有参数时,您需要为它定义一个默认构造函数以进行编译。

关于c++ - C++模板构造函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6067289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com