2016-05-14 94 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)是常量:

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

您需要從第二個參數中刪除const

​​
+0

哇!它的工作..這只是一個愚蠢的事情.. –