2016-05-14 4 views
2

私は友人の>>オペレータをテンプレートで過負荷にしようとしています。私はそれをインラインで定義したくありません。C++のテンプレートのフレンド抽出演算子(>>)のオーバーロード方法

私は以下のコードで定義されたadd()メソッドの助けを借りて同じことを試みました。それはうまく動作します。私は>>オペレータが同じことをしたいと思います。

次は私のコードです:

#include<iostream> 

template<class T>class Demo; 
template<class T> 
std::ostream& operator<<(std::ostream&, const Demo<T> &); 
template<class T> 
std::istream& operator>>(std::istream&, const Demo<T> &); 

template<class T> 
class Demo { 
private: 
    T data; // To store the value. 
public: 
    Demo(); // Default Constructor. 
    void add(T element); // To add a new element to the object. 
    Demo<T> operator+(const Demo<T> foo); 
    friend std::ostream& operator<< <T>(std::ostream &out, const Demo<T> &d); 
    friend std::istream& operator>> <T>(std::istream &in, const Demo<T> &d); 
}; 

template<class T> 
Demo<T>::Demo() { 
    data = 0; 
} 

template<class T> 
void Demo<T>::add(T element) { 
    data = element; 
} 

template<class T> 
Demo<T> Demo<T>::operator+(const Demo<T> foo) { 
    Demo<T> returnObject; 
    returnObject.data = this->data + foo.data; 
    return returnObject; 
} 

template<class T> 
std::ostream& operator<<(std::ostream &out, const Demo<T> &d) { 
    out << d.data << std::endl; 
    return out; 
} 

template<class T> 
std::istream& operator>>(std::istream &in, const Demo<T> &d) { 
    in >> d.data; 
    return in; 
} 

int main() { 
    Demo<int> objOne; 
    std::cin>>objOne; 
    Demo<int>objTwo; 
    objTwo.add(3); 
    Demo<int>objThree = objOne + objTwo; 
    std::cout << "Result = " << objThree; 
    return 0; 
} 

実際の問題

友人抽出演算子(>>)をオーバーロードしようとして以下のように、コンパイラはエラーを示しているが:

 
testMain.cpp:52:15: required from here 
testMain.cpp:46:8: error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream}' and 'const int') 
    in >> d.data; 
     ^

期待される出力

 
Result = 59 

RUN SUCCESSFUL (total time: 49ms) 

参照

答えて

4

問題はテンプレートとは関係ありません。

operator>>は右側のデータを変更しますが、そのパラメータはconstと宣言しているため、オペレータは変更できません。コンパイルエラーがさえ(d.data)の値が変更されると述べているのconstです:

testMain.cpp:46:8: error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream}' and 'const int')

あなたは二番目のパラメータからconstを削除する必要があります。

​​
+0

うわー!それは働いた..それはばかげたことだった.. –

関連する問題