Answer the question
In order to leave comments, you need to log in
How to declare an operator overload outside of a C++ class?
How to declare an addition operator for two classes, provided that the operator itself must be declared OUTSIDE the class?
Tried like this, gives an error that I can not access the fields a and b. With this played for a long time, hands fall.
class Zespolona {
private:
double a, b;
public:
int getA () {
return a;
}
int getB () {
return b;
}
int setA (int i) {
a = i;
}
int setB (int i) {
b = i;
}
Zespolona operator+(Zespolona q);
Zespolona operator-(Zespolona q);
};
Zespolona operator +(Zespolona q) {
double aa = q.getA();
aa += a;
double bb = q.getB();
bb += this->b;
return q;
}
Zespolona operator -(Zespolona q) {
double aa = q.getA();
aa -= this->a;
double bb = q.getB();
bb -= this->b;
return q;
}
Answer the question
In order to leave comments, you need to log in
Zespolona operator+(const Zespolona& left, const Zespolona& right) { ... }
Zespolona operator-(const Zespolona& left, const Zespolona& right) { ... }
friend Zespolona operator+(const Zespolona& left, const Zespolona& right);
friend Zespolona operator-(const Zespolona& left, const Zespolona& right);
#include <iostream>
using namespace std;
class Zespolona
{
public:
Zespolona(double _a = 0, double _b = 0) :a(_a), b(_b) {}
void print() {cout << a << " " << b << endl;}
private:
double a, b;
friend Zespolona operator+(const Zespolona& l, const Zespolona& r);
};
Zespolona operator+(const Zespolona& l, const Zespolona& r)
{
return Zespolona(l.a+r.a, l.b+r.b);
}
int main()
{
Zespolona one(1,2), two(3,4);
Zespolona three = one + two;
three.print();
system("pause");
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question