2016-05-14 97 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

哇!它的工作..这只是一个愚蠢的事情.. –