2016-05-14 3 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 из второго параметра:

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

... 

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

... 

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

Wow! Это сработало. Это была просто глупая вещь. –

Смежные вопросы