是否有可能重载添加操作符(+)以添加数组?例如:数组的重载操作符
double operator+ (double a[], double b[])
{
double c[];
c[] = a[] + b[];
return c;
}
是否有可能重载添加操作符(+)以添加数组?例如:数组的重载操作符
double operator+ (double a[], double b[])
{
double c[];
c[] = a[] + b[];
return c;
}
号
类型的“T的阵列” A参数被调整时,在编译时,键入“指针T”,所以你的宣言:
double operator+ (double a[], double b[])
真正含义是:
double operator+ (double *a, double *b)
而且至少GCC不,你不能定义指针类型的重载operator+
(这么认为,我相信这是正确的)。
你也不能声明一个数组类型作为其返回类型的函数;如果你尝试,它不会被调整为指针类型,它只是非法的。
您可以定义带有某些容器类型参数的函数(std::vector
,std::array
) - 无论如何,这可能会更有用。
如果左右操作数有不同的大小,一定要考虑一下operator+
应该怎么做。 (抛出异常是一种合理的方法。)
可以为您编写的类重载任何运算符。请记住,运算符重载只是为了使代码更具可读性,如果您的运算符做的事情不是非常明显,那么您可能应该重载它。对于这个特定的一个,你正在考虑你可能必须为数组编写自己的包装类。您不能直接重载它,因为已经为指针定义了operator +
。你可能能够重载operator +
为载体或阵列的数据类型在C++
不,你不能。 但你可以写一个类,封装阵列是这样的:
#include <iostream>
#include <algorithm>
class Array {
int* arr;
int arr_size;
public:
Array(int n): arr(new int[n]), arr_size(n) {}
~Array(){ delete[] arr; }
int& operator[](int n) { return arr[n]; }
Array operator+(Array& other) {
Array to_return(arr_size);
for(int i=0 ; i < std::min(arr_size, other.arr_size) ; i++)
to_return[i] = arr[i] + other[i];
return to_return;
}
};
int main() {
int tmp1[] = {1, 2, 3, 4};
int tmp2[] = {5, 6, 7, 8};
Array arr(4), arr2(4);
for(int i=0 ; i < 4 ; i++) {
arr[i] = tmp1[i];
arr2[i] = tmp2[i];
}
for(int i=0 ; i < 4 ; i++)
std::cout << (arr + arr2)[i] << ' ';
return 0;
}
输出:
6 8 10 12
使用C++ 11,你可以使用['std :: array'](http://en.cppreference.com/w/cpp/container/array)。 – dyp
@DyP:感谢您的评论!我不知道那件事。 –
如果右边的操作数比左边的操作数短,你的'operator +'会有问题。而在析构函数中,不应该'删除arr;'删除[] arr;'? –
你不能重载全球运营商服用非类类型的操作数。幸运的是std::vector<T>
(这是类类型的),我们可以改用:
#include <vector>
#include <algorithm>
#include <iostream>
template <typename T>
std::vector<T> operator +(std::vector<T> lhs, std::vector<T> rhs)
{
std::vector<T> temp;
temp.insert(temp.end(), lhs.begin(), lhs.end());
temp.insert(temp.end(), rhs.begin(), rhs.end());
return temp;
}
int main()
{
std::vector<int> x{1, 2, 3}, y{4, 5, 6};
std::vector<int> z(x + y);
for (auto a : z)
std::cout << a << ' '; // 1 2 3 4 5 6
}
这里是一个demo。
我会让参数不需要一个左值。 – chris
如果你使用的是C++ 11,你还可以提到'std :: array' ..好像没有人喜欢/记住它? – dyp
@DyP我会提到它,但我实施它时遇到了麻烦。 – 0x499602D2
不是直接。原则上,你可以写带(引用)阵列功能:
// returns a[0]*b[0] + a[1]*b[1] + ... + a[N-1]*b[N-1]
template <int N>
double innerProduct(double const (& a)[N], double const (& b)[N])
{
double sum = 0;
for (size_t i = 0; i < N; ++i) sum += a[i] * b[i];
return sum;
}
但有几个问题:
operator+
(或任何其他操作)的内置类型,如果至少有一个参数是用户定义的(数组不是这种情况),则只能这样做。见例如http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=256。因此,无论是将数组包装在用户定义的类型中,还是使用常规函数(如addInto
)。对于返回值,要么传递一个结果数组作为参数填充,要么返回其他类型,如std::vector
。
例子:
// c[0]=a[0]+b[0]; c[1]=a[1]+b[1]; ... c[N-1]=a[N-1]+b[N-1];
template <int N>
void addInto(double const (& a)[N], double const (& b)[N], double (& out)[N])
{
for (size_t i = 0; i < N; ++i) out[i] = a[i] + b[i];
}
你处理生阵列。问题是你不知道数组的大小。和“a [] + b [];”不起作用:) –