Ошибка оператора C ++ - PullRequest
       33

Ошибка оператора C ++

0 голосов
/ 13 марта 2011

получая эту ошибку:

C: \ CodeBlocks \ kool \ praks3 \ vector.h | 62 | error: передача 'const Vector <2u>' в качестве аргумента 'this' для std :: string Vector:: toString () [with short unsigned int n = 2u] 'сбрасывает квалификаторы |

с этим кодом:

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

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

        Vector();
        Vector(std::vector<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;
}

Ответы [ 3 ]

4 голосов
/ 13 марта 2011

Сделать метод toString const:

std::string toString() const;

и

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

Это потому, что вы добавляете квалификатор const к Vector в operator<<. Вам разрешено вызывать const квалифицированных методов только для const квалифицированных объектов.

1 голос
/ 13 марта 2011

Это потому, что ваш вектор объявлен как const, а ваш оператор toString не является методом const. Поэтому вызов этого метода запрещен с постоянным мгновением. Если вы не редактируете вектор при преобразовании его в строку, вы должны объявить его как метод const:

std::string toString() const;
0 голосов
/ 13 марта 2011

Если у вас есть const Foo, вы можете вызывать только const функции-члены на нем. Так объявите это как std::string toString() const.

...