C++ 如何使+;运算符(友好),以便将数组元素的值添加到类对象的字段?
我有课。此类中有2个字段。 我有一个整数数组。我的任务是重载友好的“+”运算符,以便可以添加字段值使用数组元素的值从数组中删除 例如:C++ 如何使+;运算符(友好),以便将数组元素的值添加到类对象的字段?,c++,class,operator-overloading,C++,Class,Operator Overloading,我有课。此类中有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(); re
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;
}
#包括
#包括
使用名称空间std;
阶级金字塔{
公众:
双x,h,a;
金字塔{
x=h=a=3;
}
金字塔(双p,双k,双q){
x=p;
h=k;
a=q;
}
金字塔(const金字塔和obj){
这->x=对象x;
这->h=对象h;
本->a=对象a;
}
棱锥体和运算符=(棱锥体和对象){
如果(此!=&obj){
这->x=对象x;
这->h=对象h;
本->a=对象a;
}
归还*这个;
}
棱锥运算符+(常数棱锥和b){
金字塔温度;
温度x=此->x+b.x;
温度h=此->h+b.h;
温度a=此->a+b.a;
返回温度;
}
金字塔和运算符*(int chislo){
这->x*=chislo;
这->h*=chislo;
这->a*=chislo;
归还*这个;
}
棱锥体和运算符++(int值){
这个->x++;
这个->h++;
这个->a++;
归还*这个;
}
~Pyramid(){
}
私人:
双倍Sb=10;
};
int main(){
setlocale(0,“”);
int-arr[]{1,2,3,4,5};
金字塔p2;
p2=arr[3]+p2;
返回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
。否则,示例中的数组就没有意义了。重载友好的“+”运算符,以便可以添加值从数组到类的字段值
或
作为数组元素的int和不作为数组元素的int之间没有区别,因此一个简单而等效的示例是
a=1+a代码>。数组在这里完全不重要。您想重载向类中添加的int
。这个int
是否来自某个数组,或者来自某个函数,或者来自某个指针,对于重载来说是完全无关的。将注意力集中于在int
和类之间重载操作符+
。此重载与任何其他重载之间完全没有本质区别,因此,如果您已经知道如何重载某些运算符,您应该能够自己实现它,您已经知道需要知道的所有内容。”添加字段值**从数组**中,数组元素的值“与arr[0]+a相矛盾,老实说,还不是很清楚。我试着把你建议的超负荷加入到我的课堂上,但没有任何效果。我编辑了这个问题。添加了一个类接口。问题是我做错了什么?或者你的重载在我的课堂上不起作用,因为为此你需要完成一些事情?如果你真的需要这个p2=4+p2代码>,@VladfromMoscow已经回答了你的问题。问题中的数组令人困惑。
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] };
}