Pra*_*nny 3 c++ templates generic-programming
我试图>>用模板重载friend 操作符.我不想内联定义它.
我曾尝试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;
}
Run Code Online (Sandbox Code Playgroud)
实际问题
在尝试重载友元提取operator(>>)时,编译器会显示错误,如下所示:
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)
参考
"在C++中重载提取运算符>> [duplicate]"定义如何重载>>运算符.但它没有提到它与模板的用法.
"为模板类重载friend operator <<"定义了如何重载<<运算符,但不是>>.
"重载提取运算符"也未涵盖模板概念.
该问题与模板无关.
operator>>修改右侧的数据,但是您将该参数声明为const,因此操作员无法修改它.编译器错误甚至声明要修改的值(d.data)是const:
testMain.cpp:46:8:错误:'运算符>>不匹配(操作数类型是'std :: istream {aka std :: basic_istream}'和'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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |