我又来求助了:涉及到的知识:泛型编程,模板类,操作符重载,代码和问题在帖子里面
代码如下:程序代码:
#include <iostream> #include <iterator> using namespace std; template <typename T> class complex { public: //complex(){real = 0;imag = 0;} complex(T oreal,T oimag) { real = oreal; imag = oimag; } //template<typename T2> complex operator+ (complex<T> c2) { c2.real=real+c2.real; c2.imag=imag+c2.imag; return c2; } public: inline T getReal(){return real;} inline T getImag(){return imag;} private: T real; T imag; }; namespace std { template <typename T2> std::ostream& operator<< (std::ostream& os, const complex <T2> c) { return os<<c.getReal()<<"+"<<c.getImag()<<"i"; } } int main() { complex<float> a(10,5); complex<float> b(2.2,6.0); complex<float> c=a+b; cout<<c<<"\n"; return 0; }
报错信息:
return os<<c.getReal()<<"+"<<c.getImag()<<"i"; discards qualifers
去掉const 就能执行,不去掉const就执行不了,求大神分析,对const的理解还不够好。