Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板类及;模板功能:Point&;欧几里德距离_C++_Function_Class_Templates - Fatal编程技术网

C++ 模板类及;模板功能:Point&;欧几里德距离

C++ 模板类及;模板功能:Point&;欧几里德距离,c++,function,class,templates,C++,Function,Class,Templates,我需要帮助理解为什么我的程序不起作用。我觉得这个问题潜伏在我写得不好的模板函数中,我想纠正它 Point类通过以下方式初始化: Point<int, 2> p1; //where int is the type and 2 is the dimension (in this case 2d) 点p1//其中int为类型,2为尺寸(在本例中为2d) 在我的主函数中,我初始化点并向点数组中的每个值添加值(例如p1.arr[0]=3;这类似于x=3),然后我尝试使用我的函数并将其打印出

我需要帮助理解为什么我的程序不起作用。我觉得这个问题潜伏在我写得不好的模板函数中,我想纠正它

Point类通过以下方式初始化:

Point<int, 2> p1; //where int is the type and 2 is the dimension (in this case 2d)
点p1//其中int为类型,2为尺寸(在本例中为2d)
在我的主函数中,我初始化点并向点数组中的每个值添加值(例如p1.arr[0]=3;这类似于x=3),然后我尝试使用我的函数并将其打印出来,但程序不会打开任何内容,编译器也不会说错误是什么

#include <iostream>
#include <cmath>
using namespace std;

template<typename T, int n>
class Point
{
public:
    int dimen = n;
    T arr[n];
    Point<>(){};
};

template<typename A>
double euclidean_distance(A a, A b){
    double k = 0;
    for (int i = 0; i < a.dimen; ++i){ //neglecting the fact that a and b may be of
        double op = (b.arr[i] - a.arr[i]); //different dimensions
        k += pow(op, 2);
    }
    return sqrt(k);
}
#包括
#包括
使用名称空间std;
模板
类点
{
公众:
int-dimen=n;
T arr[n];
点(){};
};
模板
双欧氏距离(A,A,b){
双k=0;
对于(inti=0;i
欧几里德距离方程基于所分析两点的尺寸:

在二维空间中:sqrt((x2-x1)^2+(y2-y1)^2)


在三维空间中:sqrt((x2-x1)^2+(y2-y1)^2+(z2-z1)^2)

您的
语法不正确。您可能希望它看起来像:

template<typename T, int n>
struct Point
{
    static const int dimen = n;
    T arr[n];
    Point(){}; // <== note: no <>
};
或者明确地使函数只取
s:

template <typename T, int DIM>
double euclidean_distance(const Point<T,DIM>& a,
                          const Point<T,DIM>& b)
{
    double k = 0;
    for (int i = 0; i < DIM; ++i) {
       // etc.
    }
}
模板
双欧几里得距离(常数点和a,
康斯特角酒店
{
双k=0;
对于(int i=0;i
那么问题出在哪里?顺便说一句,您不需要在每个点对象中存储点的尺寸。您可以使用静态数据成员来实现这一点。老实说,您甚至不需要成员,它是类型的一部分。无论如何,一个问题会很有帮助。不过,OP的代码应该在不做修改的情况下“工作”。@juanchopanza至少,构造函数是错误的。我不确定OP使用的是C++11,所以
dimen
声明也可能是错误的。
template <typename T, int DIM>
double euclidean_distance(const Point<T,DIM>& a,
                          const Point<T,DIM>& b)
{
    double k = 0;
    for (int i = 0; i < DIM; ++i) {
       // etc.
    }
}