【发布时间】:2021-04-10 16:03:17
【问题描述】:
我想创建一个临时数组对象,其数组长度等于 arr1 和 arr2 的长度之和。我该怎么做? 以下函数在类数组中被声明为友元。
template<class T1, int l1>
array<T1, l1> operator +( const array<T1, l1> &arr1, const array<T1, l1> &arr2 )
{
int add= arr1.size()+ arr2.size();
array<T1, add> temp;
........
}
这里的 size() 成员函数只是简单地返回数据的长度。 类声明是:
template<class T, int length>
class array
{
T *data{};
public:
//Overloaded assignment operator taking arr object as parameter
template<class T1, int l1>
array& operator=(const array<T1, l1> &arr_copy);
template<class T1, int l1>
friend array<T1, l1> operator +( const array<T1, l1> &arr1, const array<T1, l1> &arr2 );
....Constructors and member functions....
};
这应该可以在 main()->
arr3 = arr1 + arr2;
有人知道可以做什么吗? 返回类型解析器在哪里很重要?
【问题讨论】:
-
如果值仅在运行时已知,则短答案是 no。模板在编译时解析。
-
你能建议一种我可以重载 + 运算符以按需要工作的方法吗?
-
这正在缓慢但肯定会变成XY Problem
-
@PaulMcKenzie 我并不是要专注于某个特定的 Y。我完全陷入了这个问题。如果可以的话,请给我指路
-
首先,为什么模板化的
array类有T* data?那不应该只是T data[length];吗?这个类看起来很奇怪,因此你应该准确地说明你想用这个array类完成什么。
标签: c++ templates operator-overloading c++17 c++20