Overloading + correctly in c++ - c++

I have created class which represents line aX + bY = c and I wanted overload + operator to higher the line(return higher Line so I have done that below but compilator says invalid use of this
class Linia{
public:
double a,b,c;
Linia (double a, double b, double c){
this->a = a;
this->b = b;
this->c = c;
}
friend Linia operator+ (double i){
return new Linia(a, this->b, this->c + i/this->b);
}
};
I would like to return new Linia object which is has fields like shown above i is int i do not want to modify original object

You have some basic syntax issues.
this is a pointer so you need to use -> to dereference it.
I assume you mean this->c + i.c instead of this->c + i
You don't need to (and probably shouldn't) have the operator be a friend.
Operators that return a new instance (like operator+) should return by value, not allocate on the heap.
Operators generally take parameters as const references (since you shouldn't be modifying the operands).
I think you mean to have something like this:
class Linia{
public:
double a,b,c;
Linia (double a, double b, double c){
this->a = a;
this->b = b;
this->c = c;
}
Linia operator+ (const Linia& i){
return Linia(this->a, this->b, this->c + i.c / this->b);
}
};
which you can clean up to be something like this:
class Linia{
public:
double a,b,c;
Linia (double a, double b, double c)
: a(a), b(b), c(c)
{ }
Linia operator+ (const Linia& i){
return Linia(a, b, c + i.c / b);
}
};

There are at least two problems in your code. First, you've declared operator+ to be a friend, so it is a free function, with no this. Regretfully, from the code, I'm not able to figure out what you're trying to do (overload unary + or overload binary +), so it's difficult to say more. Second, you're trying to return the results of new, which is a pointer, not an object type. operator+ should always return an object type, so you don't want the new.

Assuming that your operator+ is a binary operator that takes two Linias as input and returns a Linea having added coefficients, you may want to define a free function operator+ overload, with proper const correctness of the input Linias, like this:
Linia operator+(const Linia& lhs, const Linia& rhs)
{
return Linia
(
lhs.a + rhs.a,
lhs.b + rhs.b,
lhs.c + rhs.c
);
}

Since you declared it as a friend, your addition operator is not a member function, hence it must take two parameters, and has no access to this:
friend Linia operator+ (const Linia& lhs, const Linia& rhs)
{
return Linia(lhs.a, lhs.b, lhs.c + rhs/lhs.b);
}
This follows the logic in your code but will only work if there is an operator double operator/(const Linia& lhs, double). Something that intuitively would make sense would be
friend Linia operator+ (const Linia& lhs, const Linia& rhs)
{
return Linia(lhs.a+rhs.a, lhs.b+rhs.b, lhs.c + rhs.c);
}
Finally, you could avoid the friend declaration completely and just declare the operator as a standard non-member function. It doesn't access any private or protected data, so it doesn't need to be a friend.

Related

Overloading operators outside of the class

So, i have a simple class:
class complex{
private:
double a,b;
public:
void setA(double a){ this->a=a; }
void setB(double b){ this->b=b; }
double getA(){ return a; }
double getB(){ return b; }
friend complex operator+(const complex&, const complex&);
};
And i have the actual overloaded operator here:
complex operator+(const complex& x, const complex& y){
complex c;
c.a=x.a+y.a;
c.b=x.b+y.b;
return c;
}
I must have the operator overloaded outside of the function. In order to have access to private variables (those also HAVE to be private) I befriended the class with the function. I don't know if that's correct way to do such things, but at least it works.
I want to be able to add an integer to both members. In main():
complex a;
a.setA(2);
a.setB(3);
a+5;
Would result in having a.a=7 and a.b=8. Such overload inside the class is quite easy to make (Again, don't know if that's good solution, if not please correct me):
complex operator+(int x){
this->a+=x;
this->b+=x;
}
But I have no idea how to make it outside of the class because i can't use "this" pointer.
The usual approach to this sort of problem is to have member functions that define the reflexive version of arithmetic operators and free functions that define the non-reflexive version, implemented with the reflexive version. No friend declarations needed. For example:
class complex {
public:
complex& operator+=(const complex& rhs) {
x += rhs.x;
y += rhs.y;
return *this;
}
private:
double x, y;
};
complex operator+(const complex& lhs, const complex& rhs) {
complex result = lhs;
result += rhs;
return result;
}
Having a+5 change the value of a is unusual, but if that's really wha you want, make operator+(int) a member. However, users would typically expect that a+5 would leave a unchanged, and that a += 5 would modify a.

Using a Friend Operator Assignment and private variable is inaccessible

I am attempting to get the "sum += A" to work in my code I am learning about writing operators but mainly dealt with objects on the left side so because of the sum being a double type I am unsure on how to code my operator to add the value of sum with the balance variable in the bank object and return the sum in the operator.
In my main I have
double sum = 0;
Bank A("Tom", 500.50);
Bank B("Sam", 123.45);
sum += A;
sum += B;
cout << sum << endl;
In my header and implementation file I have
class Bank{
char name[31];
double balance;
public:
friend double operator+=(double, const Bank&);
};
double operator+=(double a, Bank& rhs) {
a += rhs.balance;
return a;
}
I have tried using it without a friend but I am unsure of the correct syntax for having a double value when working with assignment operators. Any help would be appreaicated.
You have a couple of problems.
First - your friend declaration and your method definition don't match (you missed out a const). This means that the method definition is not a friend.
Second - the += operator needs to take its first parameter as a reference, so it can update it. It should also return a reference.
So you should end up with
...
friend double & operator+=(double &, const Bank&);
};
double & operator+=(double &a, const Bank& rhs) {
a += rhs.balance;
return a;
}
In your implementation of operator+=, you are changing a local copy of the variable. It doesn't change the variable in the calling function. You need to use:
double& operator+=(double& a, const Bank& rhs) {
a += rhs.balance;
return a;
}
Also, you need to provide a constructor in Bank to be able to construct instances of the class, something like:
Bank(char const* n, double b) : balance(b)
{
std::strcpy(name, n);
}

operator overloading and non-member functions c++

I have written a class for complex numbers in which I have overloaded the operator + and everything works fine, however I need to implement this as a non-member function and I am not sure how, or why there is a benefit of doing so.
Here is my code .h:
class Complex
{
private:
double a;
double b;
public:
Complex();
Complex(double aGiven);
Complex(double aGiven, double bGiven);
double aGetValue();
double bGetValue();
double operator[](bool getB);
Complex add(Complex &secondRational);
Complex operator+(Complex &secondRational);
}
.cpp:
Complex Complex::add(Complex &secondRational)
{
double c = secondRational.aGetValue();
double d = secondRational.bGetValue();
double anew = a+c;
double bnew = b+d;
return Complex(anew,bnew);
}
Complex Complex::operator+(Complex &secondRational)
{
return add(secondRational);
}
Any help on how to make these as non-member functions will be greatly appreciated!
Here is the addition operator outside of the class:
Complex operator+(const Complex& lhs, const Complex& rhs) {
//implement the math to add the two
return Complex(lhs.aGetValue() + rhs.aGetValue(),
lhs.bGetValue() + rhs.bGetValue());
}
Of course you will need to declare aGetValue() and bGetValue() as const:
double aGetValue() const {return a;}
double bGetValue() const {return b;}
The usual approach to arithmetic operations is to define the reflexive versions of the operators as members and the pure versions as non-members, implementing them with the reflexive versions:
class complex {
public:
const complex& operator+=(const complex& rhs) {
real += rhs.real;
imag += rhs.imag;
return *this;
}
};
complex operator+(const complex& lhs, const complex& rhs) {
complex res(lhs);
res += rhs;
return res;
}
How is explained above by pippin1289.
Why is explained below:
Imagine one need to use object of class as
Complex c3 = 5 + c1;// for c3 object c1's real part (a) added with 5
As C++ preserve order of operand. Compiler resolve above addition call as
5.operator+ (const Complex & other);// which is not possible
Hence, overload it via free function.
Your class is exposing necessary information via public interface such as aGetValue() and bGetValue.
Hence, this free overloaded + operator function need not be friend of class.
Additionally, Prefer non friend non member function over member function as it helps reduce degree of encapsulation.
This is explained here ==> http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197?pgno=1
You can declare a friend to your Complex class
class Complex {
// blah....
friend Complex operator+(Complex const& a, Complex const & b);
};
The overloaded operator can access the private members of Complex.

c++ Operator overloading,

Whats wrong with my code shown below? please somebody throw some light. Thanks for your time !
#include<iostream.h>
using namespace std;
struct mydata{
int mx;
mydata(int x = 0){}
mydata operator+(const mydata& rhs){
mydata temp(rhs);
return temp;
}
operator int() const{ return mx; }
operator double() const{ return mx; }
};
int main(){
mydata d;
mydata r = d + 5; // L1
5 + d; // L2
d + d; // L3
}
First, you haven't stated what the problem is, but presumably you want an operator+ that sums the mx values of two mydata objects:
mydata operator+(const mydata& rhs){
return mydata (mx + rhs.mx);
}
Next, I would suggest making this a non-member function, so that the LHS and RHS get treated in the same way, fixing the problem in L2:
mydata operator+(const mydata& lhs, const mydata& rhs){
return mydata (lhs.mx + rhs.mx);
}
Finally, you will have an ambiguous overload remaining, because the compiler cannot decide whether to use the built-in operator+(int,int) or your own operator+(const mydata&, const mydata&). You can fix this by removing the cast operators int() and double().
See demo here.
The problem (stated the comment) is that compiler doesn't know which + you want to execute:
(double)d + 5
or
(int)d + 5
In order to resolve this ambiguoity, you should point the type conversion, or replace one of these operators by a named function:
operator int() const{ return mx; }
operator double() const{ return mx; }
If you want instead use d + mydata(5) you should write so, because the above variants are more likely to be applied
You could provide a few non-member operator+ to enable operator+ with different data type:
mydata operator+(const mydata& lhs, const mydata& rhs){
return mydata (lhs.mx + rhs.mx);
}
mydata operator+(int mx, const mydata& rhs){
return mydata (rhs.mx+mx);
}
mydata operator+(const mydata& lhs, int mx){
return mydata(lhs.mx+mx);
}
You can't do 5 + d. 5 can not be converted to class object like this. For this you need to get the operator + definition out of the class method. (in my knowledge preferably friend).

How do I most efficiently return multiple values from an overloaded operator? (C++)

I have a class "complex" that contains a Real and an Imaginary value. I'm trying to overload the + operator so I can add real to real and imaginary to imaginary, but I'm banging my head against a wall here.
In the function, I can get the values easy. Returning them however, is a bitch.
My plan is to overload the '=' operator, too, so I can go
complex a, b, c;
(set a and b)
c = a + b;
then have a+b return a complex, then have complex c equal the complex returned by a+b
Any opinion on whether that's a viable path?
Any opinion on whether it can be done easier?
Return them as a complex! e.g.
const complex operator+(const complex &a, const complex &b)
{
return complex(a.re + b.re, a.im + b.im);
}
You shouldn't need to overload operator=; the compiler will generate one for you that does an element-by-element copy, which will probably suffice for a complex class.
I'm not sure I understand the problem. Do you have a complex class?
struct complex
{
complex(float real, float imag) :
real(real), imag(imag)
{}
// first make the mutating version
complex& operator+=(const complex& rhs)
{
real += rhs.real;
imag += rhs.imag;
return *this;
}
float real, imag;
};
// then use that for the non-mutating version
complex operator+(complex lhs, const complex& rhs)
{
lhs += rhs;
return lhs;
}
This is, of course, just an exercise; we have std::complex.
What's wrong with overloading the + operator:
complex operator+(const complex& a, const complex& b) const {
return complex(a.real + b.real, a.imag + b.imag);
}
And the operator=() similarly? (but the compiler give you this by default)
complex& operator=(const complex& a) {
real = a.real;
imag = a.imag;
return *this;
}
It is viable but there is already complex class in standard library. Reuse it or at least have a look how the operator overloading is done there.