gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:03:07 25 4
gpt4 key购买 nike

我有一个类。这个类有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.

如何重载 + 运算符来完成此任务?我对此完全没有任何想法。

类接口(interface)代码:
#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 ) .

关于c++ - 如何重载 + 运算符(友好),以便可以将数组元素的值添加到类对象的字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61578317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com