How do I use the + overload operator in C++ to add two arrays? Hi I\'m trying to
ID: 3821561 • Letter: H
Question
How do I use the + overload operator in C++ to add two arrays?
Hi I'm trying to use the overload operator to add 2 arrays, here's the snippet from the code I'm writing now and its giving a blank when I make the two objects and add them together with a third
class Sally
{
private:
int arr[10][10];
int x, y;
public:
mat operator +(mat);
};
Sally Sally::operator+(Sally sally2) {
Sally brandNew;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
brandNew[i][j].arr = arr[i][j] + sally2.arr[i][j];
}
}
return (brandNew);
}
//code to make array and read
Sally obj1, obj2, obj3
obj3 = obj1 + obj2;
Explanation / Answer
I have added few method to fill and print array and constrcutor to demonstarte that operator + is correctly fixed.
#include <iostream>
using namespace std;
class Sally
{
private:
int arr[10][10];
int x, y;
public:
Sally(int a, int b) { x= a; y = b;}
Sally() {x = 10; y = 10;}
Sally operator +(Sally const &obj);
void fillArray(int n)
{
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
arr[i][j] = n;
}
}
}
void printArray()
{
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
}
};
Sally Sally::operator+(Sally const &obj) {
Sally brandNew;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
brandNew.arr[i][j] = arr[i][j] + obj.arr[i][j];
}
}
return (brandNew);
}
int main()
{
//code to make array and read
Sally obj1(10, 10), obj2(10, 10), obj3;
obj1.fillArray(10);
obj2.fillArray(20);
obj3 = obj1 + obj2;
cout << "printing obj3 after addition" << endl;
obj3.printArray();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.