2011-03-13 1 views
0

このエラー取得:C++オペレータエラー

C:\コードブロック\クール\ praks3 \ vector.h | 62 |エラー:STD」の 'この' 引数として 'constのベクトル< 2U>' 渡す::文字列をVector :: toString()[短い符号なしint n = 2u] '修飾子を破棄します。このコードで

std::string toString() const; 

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

あなたはoperator<<Vectorconst修飾子を追加しているためです。

#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

おめでとう。だから、あなたの質問は何ですか?私は上記の1つの疑問符が表示されません。 – AnT

答えて

4

toString方法constしてください。 const修飾オブジェクトでconst修飾メソッドにのみ呼び出すことができます。

0

const Fooがある場合は、constメンバー関数のみを呼び出すことができます。したがって、std::string toString() constと宣言してください。

1

あなたのベクトルはconstとして宣言されていますが、toString演算子はconstメソッドではありません。 したがって、このメソッドの呼び出しはconstインスタントで禁止されています。 文字列に変換しながら、あなたはベクトルを編集しない場合は、constのメソッドとしてそれを宣言する必要があります。

std::string toString() const;