If a class name is DataContainer how should the function definition be to over load the divide operator / as shown in main ? The goal is to divide each array item by a constant value in main. Thanks for any help or advice on this problem.
I don't know what your DataContainer looks like, but possibly like this:
1 2 3 4 5 6
DataContainer operator/(DataContainer arr, int value)
{
for (size_t i = 0; i < arr.size(); ++i)
arr[i] += value;
return arr;
}
Since it needs to pass back a new DataContainer you may as well pass a copy in, add the value and pass that back.
Or maybe like this, if you also want a /=.
1 2 3 4 5 6 7 8 9 10 11 12
// member function
DataContainer& DataContainer::operator/=(int value)
{
for (size_t i = 0; i < arr.size(); ++i)
data[i] += value; // assuming contained array is called data
return *this;
}
DataContainer operator/(DataContainer container, int value)
{
return container += value;
}
The first function works, but the second one doesn't because the compiler only allows one argument for overloading operators.
This one compiles with no errors, but does not divide each number by the constant in main. It does put all the values of each item in the array on the right into the values on the left, ie
DataContainer d1, d2 then d1 = d2:
1 2 3 4 5 6
DataContainer& DataContainer::operator/=(int value)
{
for (size_t i = 0; i < arr.size(); ++i)
data[i] += value; // assuming contained array is called data
return *this;
}
I am using Visual Studio 2015. Could this be the reason I am getting an error for more than one argument passed into the function?
Thanks for your help.
Define the operator / operator outside of the class itself to let it have two arguments.
If it's defined as part of the class, then the only argument should be the (int value).
This one compiles with no errors, but does not divide each number by the constant in main
Look at what the code is doing. Don't just copy the code without understanding it. As doug4 mentioned, I believe you want to be doing division, not addition.