我想用模板超載朋友>>
運算符。我不想在內聯中定義它。如何重載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"也不包括模板概念。
哇!它的工作..這只是一個愚蠢的事情.. –