如何重载+运算符(友好),以便将数组元素的值添加到类对象的字段中
How to overload the + operator (friendly) so that you can add the value of an array element to the fields of a class object?
我有一个类。这个类中有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] };
}
相关文章:
- 数组元素打印的递归方法
- 在动态数组中添加/删除C++元素
- 静态2D数组,添加元素
- 添加数组元素:需要左键作为赋值的左操作数
- 在数组中添加元素将不接受类似的元素
- 为什么可以在长度为 0 的数组中添加定义元素 C++.
- 使用指针在功能中的数组中添加/删除元素
- C++将字符从静态数组复制到动态数组会添加一堆随机元素
- 我可以向数组指针添加元素吗
- 添加到单个数组元素-C++
- 向数组中添加元素
- 如何将文件夹中的所有img添加到CImage数组元素
- 在没有位置的数组中添加一个元素
- 向数组中添加元素,但输出错误的值
- 向二维数组中添加元素
- 如何在c++中向数组中添加元素
- 使用自增操作符添加数组元素
- 在从循环中动态获得的值之后向数组中添加一个元素
- 无法在数组中添加元素
- 数组元素从未成功添加?(C++)