我试图覆盖toString方法,就像在Java中一样。我是C ++的新手,所以尽管使用这个头文件的测试程序会编译,但它可能会有很多错误。我的目标是以“(x1,x2,x3 ...... x4)”的形式将点作为字符串返回。坐标量将从0变为n。如何更改toString()以便它不会返回“test”但会将该点的坐标返回为String?
#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <list>
#include <cmath>
using std::ostream;
using std::list;
using ::std::sqrt;
using namespace std;
template<unsigned short n>
class Point {
public:
list <float> coords;
Point <n>() = default;
Point <n>(list<float> coords){
if (coords.size()!=n) {
throw string ("Vale kordinaatide arv");
}
this-> coords=coords;
}
string toString() const {
return "Test toString";
}
float distanceFrom (Point <n> v){
float s=0;
list<float> coords;
auto it1= coords.begin();
auto it2= v.coords.begin();
while ((it1) != coords.end()){
s+=(*it1 -*it2)*(*it1-*it2);
it1++;
it2++;
}
return sqrt(s);
}
friend std::ostream& operator <<(std::ostream& out, const Point<n>& v)
{
out << "("<<"Test"<<")";
return out;
}
};
#endif