How to call my toString from operator<< ?

How do I call toString from operator<< ? I have implemented toString but I dont know how to call it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#ifndef POINT_H
#define POINT_H

// Comment this for documentation!

#include <iostream>
#include <list>
#include <sstream>
using std::ostream;

template <unsigned short n>
class Point {

public:
    std::list<float> coords = std::list<float>(n);

    Point() = default; //c++11 The default constructor is explicitly stated.

    Point(std::list<float> p);

    float distanceFrom (Point p);
    
    std::string toString();
};


template <unsigned short n>
Point<n>::Point(std::list<float> arg)
{
	coords.assign (arg.begin(), arg.end());
}


template <unsigned short n>
float Point<n>::distanceFrom (Point p) {
	//return sqrt (pow(x-p.x,2.0) + pow(y-p.y,2.0));
	return 0.0;
}

template <unsigned short n>
std::string Point<n>::toString () {
    std::stringstream ss;

    for (std::list<float>::const_iterator iterator = coords.begin(), end = coords.end(); iterator != end; ++iterator) {
	if(iterator != coords.begin()){
	    ss << ",";
	}
	ss << *iterator;
    }
    
    std::string s = ss.str();
    return s;
}

template <unsigned short n>
ostream& operator<<(ostream& out, const Point<n>& p) {
    out << "(" << p.toString() << ")";
    return out;
}
#endif 



Error I get is:
1
2
3
4
include/point.h:57:16: error: passing ‘const Point<2u>’ as ‘this’ argument of ‘std::string Point<n>::toString() [with short unsigned int n = 2u; std::string = std::basic_string<char>]’ discards qualifiers [-fpermissive]
     out << "(" << p.toString() << ")";
                ^
make: *** [obj/geometrytest.o] Error 1
Line 56: p is const. toString() is not a const function. Change line 41 to make toString() a const function.
It didn't help me (when I used const std::string Point<n>::toString ()). It still says same thing.

Is there any other way around it?
That's still not a const function. That's a const return value.
The correct version would be:
std::string Point<n>::toString() const.
Also, the same goes for the class declaration.
Thanks.

So with const functions I need to write const keyword after function args?
Yes.
Topic archived. No new replies allowed.