使用模板重载运算符
operator overloading with templates
我有一个类,它必须能够容纳一种浮点数,双精度,长超型。我想以这样一种方式重载它,以便它可以添加两个持有不同类型的实例。
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
这只是伪代码,我已经保留了不相关的位,我实际上正在尝试使用这种解决方案。
现在尝试使用时:
F<int> first(5);
F<int> second(4);
first+=second; // Works
F<int> third(5);
F<float> fourth(6.2);
fourth+=third; // wont work
我可以看到为什么这不起作用,因为它假设 rhs 参数与 lhs 的类型相同。我还可以看到在执行 int += 只要的操作时存在潜在问题,因为如果长型很大,则需要更改类型。我似乎找不到解决问题的好方法。感谢您的投入。谢谢
您
还需要将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
然后你可以做
F<int> a(4);
F<float> b(28.4);
b += a;
cout << b.a << endl; // prints 32.4
这是一个工作示例。
template <typename T>
class F{
public:
F(const T & t){a=t;}
T a;
template<typename T2>
F & operator+= (const F<T2> & rhs);
};
template<typename T>
template<typename T2>
F<T>& F<T>::operator+= (const F<T2> & rhs){
a+=(T)rhs.a;
return *this
}
编辑:
修复错误,请参阅评论
> 你可以模板化operator+=
:
template<typename G> F<T> & operator+= (const F<G> & rhs);
。假设您可以以某种方式将G
转换为T
.
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用