Reputation: 39
Here my job is to make array of objects and for him to write three operator functions, which make different operations with him. I don't know how to pass the array as parameter for each function. When I call the second operator function friend void operator+(A &x);
, it calls the constructor again, but I want to use the result from the first function.
class A{
string name;
double array[N];
int group;
public:
A();
~A();
friend A operator--(A x);
friend void operator+(A &x);
friend A operator&(A x);
};
A operator--(A x){
A z;
// some code
return z;
}
void operator+(A &x){
//here I must use the returned object z;
}
A operator&(A x){
//here I must use the returned object z;
}
void main() {
A *a;
a = new А[2];
for (int i = 0; i < N; i++){
(--a[i]);
+(a[i]);
}
}
Upvotes: 1
Views: 91
Reputation: 7802
If each object created is not being added or subtracted with another object this should work. Your original code in main() would not compile with clang so I've modified it to use a vector.
#include <iostream>
#include <string>
#include <vector>
constexpr int N = 2;
class A
{
private:
std::string name;
double array[N];
int group;
public:
A() {};
A(std::string s, int g) : name(s), group(g) {};
~A() {};
int getGroup() { return group; }
friend void operator--(A&);
friend void operator+(A&);
};
void operator--(A& a) {
--a.group;
std::cout << "overloaded operator --" << std::endl;
}
void operator+(A& a) {
a.group += 3;
std::cout << "overloaded operator +" << std::endl;
}
using namespace std;
int main(int argc, char const *argv[])
{
std::vector<A> v;
for (int i = 0; i < N; ++i) {
v.emplace_back(A{});
}
v.emplace_back(A{"my name", 5});
for (auto& i : v) {
--(i);
cout << "group: " << i.getGroup() << endl;
--(i);
cout << "group: " << i.getGroup() << endl;
+(i);
cout << "group: " << i.getGroup() << endl;
}
return 0;
}
Output:
overloaded operator --
group: -1
overloaded operator --
group: -2
overloaded operator +
group: 1
overloaded operator --
group: -1
overloaded operator --
group: -2
overloaded operator +
group: 1
overloaded operator --
group: 4
overloaded operator --
group: 3
overloaded operator +
group: 6
If you need specific values in name and group you can populate the values in a in a vector<std::pair>
or similar and then iterate that vector and emplace_back(A{p.first, p.second}). And add a constructor that accepts these values.
Upvotes: 1
Reputation: 507
Use pass by references in first and third operators as well. Like you did in the second one.
Upvotes: 0
Reputation: 1053
You should pass your array by reference - which means by adress not by value.
Here the constructor is called again because your object gets copied (then reconstructed) instead of only transferred as parameter.
Upvotes: 0