如何重载+运算符(友好),以便将数组元素的值添加到类对象的字段中

How to overload the + operator (friendly) so that you can add the value of an array element to the fields of a class object?

本文关键字:数组元素 添加 对象 字段 重载 何重载 运算符 友好      更新时间:2024-05-10

我有一个类。这个类中有2个字段。我有一个整数数组。我的任务是重载友好的"+"运算符,以便可以添加字段值​​使用数组元素的值从数组中提取。

例如:

class Test {
public:
double x, y;
Test() {
x = 0;
y = 0;
}
};
int main() {
Test a;
int arr[2] { 1, 2 };
a = arr[0] + a;
a.Show();
return 0;
}

我期望以下值:

x = 1;
y = 1.

如何使+运算符过载以完成此任务?我对此没有任何想法。

类接口代码:

#include <iostream>
#include <fstream>
using namespace std;
class Pyramid {
public:
double x, h, a; 
Pyramid() {
x = h = a = 3;
}
Pyramid(double p, double k, double q) {
x = p;
h = k;
a = q;
}
Pyramid(const Pyramid& obj) {
this->x = obj.x;
this->h = obj.h;
this->a = obj.a;
}
Pyramid& operator=(Pyramid& obj) {
if (this != &obj) {
this->x = obj.x;
this->h = obj.h;
this->a = obj.a;
}
return *this;
}
Pyramid operator+(const Pyramid& b) {
Pyramid temp;
temp.x = this->x + b.x;
temp.h = this->h + b.h;
temp.a = this->a + b.a;
return temp;
}
Pyramid& operator*(int chislo) {
this->x *= chislo;
this->h *= chislo;
this->a *= chislo;
return *this;
}
Pyramid& operator++(int value) {
this->x++;
this->h++;
this->a++;
return *this;
}
~Pyramid() {
}
private:
double Sb = 10;
};

int main() {
setlocale(0, "");
int arr[]{ 1,2,3,4,5 };
Pyramid p2;
p2 = arr[3] + p2;
return 0;
}

非类运算符+可以看起来像

Test operator +( const Test &t, double value )
{
return { t.x + value, t.y + value };
}
Test operator +( double value, const Test &t )
{
return { t.x + value, t.y + value };
}

假设类Test是聚合或具有构造函数Test( double, double )

您似乎需要实现a = a + arr。否则,示例中的数组将毫无意义重载友好的"+"运算符,以便可以添加值​​从数组到类的字段值

Test operator+ (const Test& t, const int* values) {
return { t.x + values[0], t.y + value[1] };
}

Test operator+ (const Test& t, const int (&values)[2]) {
return { t.x + values[0], t.y + value[1] };
}