2011-03-13 5 views
0

이 오류 점점 :C++ 운영자 오류

C : \ CodeBlocks \ 쿨 \ praks3 \ vector.h | 62 | 오류 : 통과 'CONST 벡터 < 2U>'표준 '의'이 '인수로 : 문자열을 벡터 :: toString() [짧은 부호없는 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; 
} 
+1

축하합니다. 그래서, 당신의 질문은 무엇입니까? 나는 위의 하나의 물음표가 보이지 않습니다. – AnT

답변

4

toString 방법 const합니다

std::string toString() const; 

하고 operator<<Vectorconst 규정을 추가하기 때문이다

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

. const 인증 된 개체에 대해 const 인증 된 메서드에만 호출 할 수 있습니다.

0

const Foo 사용자는 const 회원 기능 만 호출 할 수 있습니다. 따라서 이것을 std::string toString() const으로 선언하십시오.

1

이것은 벡터가 const로 선언 되었기 때문에 발생합니다. toString 연산자는 const 메소드가 아니기 때문입니다. 따라서이 메서드를 호출하면 const 순간이 금지됩니다. 문자열로 변환하는 동안 벡터를 수정하지 않으면 , 당신은 CONST 방법으로 선언해야합니다

std::string toString() const;