user3328230
user3328230

Reputation: 61

c++ which is of non-class type error

for the start keep in mind I am a complete rookie in c++. I have read a lot about templates and strings today, but I cant figure couple of things out. When I create a point in my test class with point<2> or any other value. I have an error: request for member 'tostring' in 'v2' which is of non-class type... 1. Why do I get that error? 2. How can make Point() = default; to make every coordinate value 0.0; Like if I have Point<1> it would be (0.0), Point<2> would be (0.0, 0.0) and so on:.

#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

Upvotes: 0

Views: 859

Answers (1)

4pie0
4pie0

Reputation: 29754

Increment iterator in a method toString and it works:

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;
        }

compiled example


The note about templates:

inside the class body you don't need to say Point<n>, just Point:

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

To print Point you have to make toString method const:

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

to enable call on a const Point. Now you can use it in operator<< :

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

Upvotes: 1

Related Questions