c++创建通用点模板

c++ creating universal point template

本文关键字:创建 c++      更新时间:2023-10-16

开始我对c++很陌生,所以可能只是一个愚蠢的语法错误。我试图创建一个头文件,在那里我想为点创建模板,这样点可以有任何数量的坐标。就像Point <2>有x和y坐标。点<3>有x,y,z等等。当我使用这个头与测试程序,它不编译。有人能帮我吗?

using std::ostream;
using std::list;
template <unsigned short n>
class Point {
public:

Point <n>() = default; 
Point <n>(list<float> coords){

    this-> coords=coords;
    }

    float distanceFrom (Point <n> p){
        float s=0;
        auto it1= coords.begin();
        auto it2= p.coords.begin();
        while ((it) != coords.end()){
            s+=(*it1 -*it2)*(*it1-*it2);
            it1++;
            it2++;
        }
    return sqrt(s);
    }
};
#endif

您引用的是未声明的类成员coords

只需将声明list<float> coords;添加到您的类中。

要解决第二个问题,您需要使sqrt声明可用。为此,您需要#include <cmath>,它将提供::std::sqrt。请记住添加using ::std::sqrt或类似的语句,以确保它被称为sqrt