我想用模板超载朋友>>
运算符。我不想在内联中定义它。如何重载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)
参考
"overloading the extraction operator >> in C++ [duplicate]"定义如何重载
>>
运算符。但它没有提及它与模板的用法。"Overloading friend operator << for template class"定义了如何过载运算符
<<
,但不是>>
。"Overloading Extraction operator"也不包括模板概念。
哇!它的工作..这只是一个愚蠢的事情.. –