c++中的非类类型错误

c++ which is of non-class type error

本文关键字:类型 错误 c++      更新时间:2023-10-16

首先请记住,我是一个完全的c++新手。我读了很多关于模板和字符串今天,但我不能弄清楚的事情。当我用point<2>或任何其他值在测试类中创建一个点时。我有一个错误:请求成员'tostring'在'v2'这是非类类型…1. 为什么会出现这个错误?2. 如何使Point() = default;使每个坐标值为0.0;例如,如果我有Point<1>,它将是(0.0),Point<2>将是(0.0,0.0)等等:

#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <list>
#include <sstream>
#include <string>
using std::stringstream;
#include <cmath>
using namespace std;

template<unsigned short n>
class Point {
public:
    list <float> coords = {0.0};
    Point <n>() = default; 
    Point <n>(list<float> coords){
        this-> coords=coords;
        }
        string toString(){
            string sone;
            ostringstream ss;
            sone.append("(");
            auto it3= coords.begin();
            while ((it3) != coords.end()){  
                ss <<  (*it3);
                sone.append(ss.str());
                ss.str("");
                }
            sone.append(")");
            return sone;
        }
        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

toString方法中的自增迭代器

string toString(){
            string sone;
            ostringstream ss;
            sone.append("(");
            auto it3= coords.begin();
            while ((it3) != coords.end()){  
                ss <<  (*it3);
                sone.append(ss.str());
                ss.str("");
                ++it3;
                ^^^
                }
            sone.append(")");
            return sone;
        }

编制示例


关于模板的说明:

在类体内你不需要说Point<n>,只说Point:

Point () = default;
Point ( list<float> coords){ //...}

要打印Point,您必须使toString方法const:

string toString() const { //... }

允许调用const点。现在你可以在operator<<:

中使用它了
 friend std::ostream& operator <<(std::ostream& out, const Point<n>& v) {
        out << v.toString();
        return out;
 }