我想重新定义最初在operator*
类中定义为朋友的Vector
函数,在派生类BigNum
中。具体来说,我想调用Vector
版operator*
,然后在BigNum
的运算符*中执行该操作的结果。这是结构的片段(再次感谢@lemmes帮助解决这个问题):
template<typename T>
class Vector
{
private:
std::vector<T> base;
public:
Vector();
Vector(const std::vector<T> vec);
Vector(const Vector& vec);
template<typename T1, typename T2>
friend auto operator*(const Vector<T1>& lhs, const Vector<T2>& rhs) -> Vector<decltype(std::declval<T1>() * std::declval<T2>())>;
};
template<typename T1, typename T2>
auto operator*(const Vector<T1>& lhs, const Vector<T2>& rhs) -> Vector<decltype(std::declval<T1>() * std::declval<T2>())>
{
typedef decltype(std::declval<T1>() * std::declval<T2>()) T3;
assert(lhs.base.size() == rhs.base.size());
Vector<T3> result;
result.base.reserve(lhs.base.size());
std::transform(lhs.base.begin(), lhs.base.end(), rhs.base.begin(), std::back_inserter(result.base),
[](const T1& e1, const T2& e2) { return e1 * e2; });
return result;
}
class BigNum : public Vector<int>
{
public:
BigNum();
BigNum(const std::vector<int> init);
~BigNum();
BigNum operator*(const BigNum& rhs);
};
#endif
BigNum BigNum::operator*(const BigNum& rhs)
{
// How can I call Vector's operator* (a friend of the Vector class)
// and then do other stuff in here?
}
#include "BigNum.h"
int main()
{
int arr1[] = {1,2,3,4,5};
int arr2[] = {10,20,30,40,50};
std::vector<int> vec1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]));
std::vector<int> vec2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]));
BigNum bn1(vec1), bn2(vec2);
bn1 * bn2; // want to call BigNum's operator* here
return 0;
}
我显然无法做Vector::operator*
之类的事情,因为它是朋友。提前谢谢!
答案 0 :(得分:1)
您可以编写static_cast<Vector<int>&>(bn1) * static_cast<Vector<int>&>(bn2)
来调用向量的重载运算符。