开发者

C++ operator error

getting this error:

C:\CodeBlocks\kool\praks3\vector.h|62|error: passing 'const Vector<2u>' as 'this' argument of 'std::string Vector::toString() [with short unsigned int n = 2u]' discards qualifiers|

with this code:

    #include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <sstream>

template <unsigned short n>
class Vector {
    public:
        std::vector<float> coords;

        Vector();
        Vector(std::vecto开发者_JS百科r<float> crds);


        float distanceFrom(Vector<n> v);

        std::string toString();

        template <unsigned short m>
        friend std::ostream& operator <<(std::ostream& out, const Vector<m>& v);
};



    template <unsigned short n>
std::string Vector<n>::toString() {
    std::ostringstream oss;

    oss << "(";
    for(int i = 0; i < n; i++) {
        oss << coords[i];
        if(i != n - 1) oss << ", ";
    }
    oss << ")";
    return oss.str();
}

template <unsigned short m>
std::ostream& operator<<(std::ostream& out, const Vector<m>& v) {
    out << v.toString(); // ERROR HEEEERE
    return out;
}


Make the toString method const:

std::string toString() const;

and

template <unsigned short n>
std::string Vector<n>::toString() const{...}

That's because you add the const qualifier to the Vector in the operator<<. You are only allowed to call const qualified methods on const qualified objects.


This is because your vector is declared as const, while your toString operator is not a const method. Therefore, calling this method is forbidden with a const instant. If you do not edit the vector while converting it to string, you should declare it as a const method :

std::string toString() const;


If you have a const Foo, you can only invoke const member functions on it. So declare it as std::string toString() const.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜