woo*_*ie1 3 c++ templates operator-overloading
我有一个类必须能够保持一种浮动,双重,长的异常.我想以这样的方式重载它,它可以添加两个持有不同类型的实例.
template <typename T>
class F{
public:
F(const T & t){a=t;}
T a;
F & operator+= (const F & rhs);
}
template<typename T>
F<T> F::operator+= (const F & rhs){
a+=rhs.a;
return *this
Run Code Online (Sandbox Code Playgroud)
这只是伪代码我已经保留了无关的位,我实际上试图使用这种解决方案.
现在尝试使用时:
F<int> first(5);
F<int> second(4);
first+=second; // Works
F<int> third(5);
F<float> fourth(6.2);
fourth+=third; // wont work
Run Code Online (Sandbox Code Playgroud)
我可以看出为什么这不起作用,因为它假设rhs参数与lhs的类型相同.我还可以看到在执行int + = long操作时存在潜在的问题,好像long很大,类型需要更改.我似乎无法找到解决问题的好方法.我很感激您的意见.谢谢
您还需要制作operator+=模板:
template <typename T>
class F{
public:
F(const T & t){ a = t; }
T a;
template<typename T2>
F& operator+=(const F<T2>& rhs);
}; // semicolon was missing
template<typename T>
template<typename T2>
F<T>& F<T>::operator+=(const F<T2>& rhs) {
a += rhs.a;
return *this; // semicolon was missing
} // brace was missing
Run Code Online (Sandbox Code Playgroud)
那你可以做
F<int> a(4);
F<float> b(28.4);
b += a;
cout << b.a << endl; // prints 32.4
Run Code Online (Sandbox Code Playgroud)