Operator overloading+ add two objects - c++

I'm trying to add two object that they are in the same class.
In the private section of the class I have two int variables
class One {
private:
int num1, num2;
public:
One operator+=(const One&); // - a member operator that adds another One object - to the current object and returns a copy of the current object
friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
};
One operator+(const One&, const One&);// - a non-friend helper operator that adds One objects without changing their values and returns a copy of the resulting One
I'm not sure I have a problem on the opeartor+ I guess
One operator+(const One &a, const One &b){
One c,d,r;
c = a;
d = b;
r += b;
r += a;
return r;
}
I think the above code is wrong, but I tried to use like b.num1 and I get compile error
error: 'int One::num1' is private
error: within this context
and I can't use b->num1 as well because the above function is not in the member function section.
error: base operand of '->' has non-pointer type 'const One'
This is how it calls in main
Result = LeftObject + RightObject;

If you have already implemented this member function:
One One::operator+=(const One&);
Then you may implement the non-member addition operator thus:
One operator+(const One& lhs, const One& rhs) {
One result = lhs;
result += rhs;
return result;
}
This can be simplified somewhat into the following:
One operator+(One lhs, const One& rhs) {
return lhs += rhs;
}
This pattern (which you can adapt for all operator/operator-assignment pairs) declares the operator-assignment version as a member -- it can access the private members. It declares the operator version as a non-friend non-member -- this allows type promotion on either side of the operator.
Aside: The += method should return a reference to *this, not a copy. So its declaration should be: One& operator+(const One&).
EDIT: A working sample program follows.
#include <iostream>
class One {
private:
int num1, num2;
public:
One(int num1, int num2) : num1(num1), num2(num2) {}
One& operator += (const One&);
friend bool operator==(const One&, const One&);
friend std::ostream& operator<<(std::ostream&, const One&);
};
std::ostream&
operator<<(std::ostream& os, const One& rhs) {
return os << "(" << rhs.num1 << "#" << rhs.num2 << ")";
}
One& One::operator+=(const One& rhs) {
num1 += rhs.num1;
num2 += rhs.num2;
return *this;
}
One operator+(One lhs, const One &rhs)
{
return lhs+=rhs;
}
int main () {
One x(1,2), z(3,4);
std::cout << x << " + " << z << " => " << (x+z) << "\n";
}

I can't see why the operator+ is wrong:
#include <stdio.h>
class One {
public:
One(int n1, int n2): num1(n1),num2(n2) {}
private:
int num1, num2;
public:
One operator+=(const One& o) {
num1 += o.num1;
num2 += o.num2;
return *this;
}
friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
void print() {
printf("%d,%d\n", num1, num2);
}
};
One operator+(const One& a, const One& b) {
One r(0,0);
r += b;
r += a;
return r;
}
int main() {
One a(1,2),b(3,4);
One r = a + b;
r.print();
}

Related

Overloading Operators

I need your help, please have a look at the following code I get error
as following:
no match for operator *(operand types are'doubles and 'lists')
this is inherited class, header file(before operator* function it worked properly)
class lists:public vectorebi
{
public:
lists (double first_);
lists (double first_, lists var_);
double operator-(const double& answer);
lists operator*(const lists &answer) const;
virtual ~lists(){};
private:
friend std::ostream& operator<<(std::ostream& os, lists& arg);
double first;
lists* var;
};
//soucre file
lists::lists(double first_){
first=first_;
}
lists::lists(double first_, lists var_){
first=first_;
var=&var_;
}
double lists::operator-(const double& answer){
double result = answer - first;
return result;
}
lists lists::operator*(const lists &answer) const
{
lists k = first * answer.first;
return k;
}
std::ostream& operator<<(std::ostream& os, lists& arg) {
os << "(" << arg.var << ")";
return os;
}
and the main ///
int main()
{
double answer1 = 15;
lists k=5;
lists answer = k * answer1; //here is an error as compiler points
cout << answer;
return 0;
}
I will appreciate your help, I am trying to multiply variable of type my class and double, is it possible?
* is a binary operator, meaning it expects 2 arguments.
When you say a * b, a becomes the first (left) argument and b becomes the second (right) argument. Effectively the function call looks like a.operator*(b).
You are doing, answer1 * k which evaluates to the call answer1.operator*(k) . This means double must have operator* overloaded for lists.
But you want it for your class lists. So you must do this in main():
lists answer = k * answer1;
And operator* must be declared as:
lists lists::operator*(const double& answer)
{
lists k = first * answer; // not sure how double * double equals lists
return k;
}
EDIT:
Regarding the error
lists* lists::var is private within this context
which you pointed out in the comments, it appears because of the inconsistent declaration of friend operator<<.
You have declared it as:
friend std::ostream& operator<<(std::ostream& os, const lists& arg); // note the `const` for `arg`
But you have defined it as:
std::ostream& operator<<(std::ostream& os, lists& arg) // `const` missing!!
{
....
}
Just add const in the definition as well, and it will work as expected.
The line:
lists answer = answer1 * k;
fails because the compiler is looking for a * overload on a double that takes lists instance. This method doesn't exist, but you can define it my creating the method outside your class:
lists operator*(double lhs, const lists &rhs)
{
return lists(lhs) * rhs;
}
NOTE: I've made rhs a const as this is best practice for operator overloads like this which do not (and should not) modify their inputs:
lists operator*(const lists &answer) const;
in the declaration and:
lists lists::operator*(const lists &answer) const
{
lists k = first * answer.first;
return k;
}
in the implementation.
NOTE: I think you meant to multiple by answer.first and otherwise the code doesn't make much sense.
Also, your streaming operator currently tries to output var which is a member variable you never initialize. I suspect you want to output first so change it to this:
std::ostream& operator<<(std::ostream& os, const lists& arg)
{
os << "(" << arg.first << ")";
return os;
}
I've made arg const as this is the recommended practice. You'll need to update your class definition to reflect this.

C++ What operators I need to overload to make this A1 += A2 * floatValue work?

What operators I need to overload to make this word?
Variables A1 and A2 both of type class A, variable floatValue is of type float.
A1 += A2 * floatValue;
I have overloaded this operators
A operator+() const;
A operator+=(const A value);
A operator*(const A value);
friend A operator*(const A val2, float val);
But, I receive error "Class A has no suitable copy constructor"
I have this constructors in my class
A();
A(float val1, float val2);
A(float value);
Thanks for answering.
Minimal example:
#include <iostream>
using namespace std;
struct foo {
float val;
foo(float val): val(val){}
foo &operator+=(foo const &other) {
this->val += other.val;
return *this;
}
friend foo operator*(foo const &lhs, foo const &rhs) {
return lhs.val*rhs.val;
}
};
int main() {
foo a = 5, b = 6;
a += b * 3;
cout << a.val << endl;
return 0;
}
see: http://ideone.com/6pD2pr
With an explicit constructor you might want to use this example instead:
#include <iostream>
using namespace std;
struct foo {
float val;
explicit foo(float val): val(val){}
foo &operator+=(foo const &other) {
this->val += other.val;
return *this;
}
friend foo operator*(foo const &lhs, float val) {
return foo(lhs.val*val);
}
};
int main() {
foo a(5), b(6);
a += b * 3;
cout << a.val << endl;
return 0;
}
see: http://ideone.com/o8Vu1d
Whenever you overload an assignment operator like
A operator+=(const A value);
you also need to define a copy constructor like
A( const A& );
The copy constructor will be used by the assignment operator.
This is part of what's known as the Rule of Three.
When you have function like this:
fun(A a);
Arguments here are passed by value, so you need to have copy constructor for A (in order to create new instance from another instance), OR you can change it to reference, so no copy constructor will be needed.
Like this:
A operator+=(const A &value);

C++ My first class operator overload, with header

im new to C++, although i do know the general C syntax. I've been trying to create a class with operator overloading. But i can't get it to work. Well partially got it to work.
Working operator overloading in same source:
//test.cpp
#include <iostream>
class Fraction
{
int gcd(int a, int b) {return b==0 ? a : gcd(b,a%b); }
int n, d;
public:
Fraction(int n, int d = 1) : n(n/gcd(n,d)), d(d/gcd(n,d)) {}
int num() const { return n; }
int den() const { return d; }
Fraction& operator*=(const Fraction& rhs) {
int new_n = n*rhs.n / gcd(n*rhs.n, d*rhs.d);
d = d*rhs.d / gcd(n*rhs.n, d*rhs.d);
n = new_n;
return *this;
}
};
std::ostream& operator<<(std::ostream& out, const Fraction& f){
return out << f.num() << '/' << f.den() ;
}
bool operator==(const Fraction& lhs, const Fraction& rhs) {
return lhs.num() == rhs.num() && lhs.den() == rhs.den();
}
bool operator!=(const Fraction& lhs, const Fraction& rhs) {
return !(lhs == rhs);
}
Fraction operator*(Fraction lhs, const Fraction& rhs)
{
return lhs *= rhs;
}
int main()
{
Fraction f1(3,8), f2(1,2), f3(10,2);
std::cout << f1 << '*' << f2 << '=' << f1*f2 << '\n'
<< f2 << '*' << f3 << '=' << f2*f3 << '\n'
<< 2 << '*' << f1 << '=' << 2 *f1 << '\n';
}
Output:
3/8*1/2=3/16
1/2*5/1=5/2
2*3/8=3/4
Source: http://en.cppreference.com/w/cpp/language/operators
Now my code, trying to apply the code from above
//vectors.h
class Vector2
{
public:
Vector2(void);
~Vector2(void);
int counter;
Vector2& operator+=(const Vector2& vec);
}
//vectors.cpp
#include "vectors.h"
Vector2::Vector2(void)
{
counter = 0;
}
Vector2::~Vector2(void)
{
}
Vector2& operator+=(Vector2& vec)//error: too few parameters
{
int new_n = counter + vec.counter;
counter = new_n;
return *this;//error: this may only be used in a non-static member function.
}
//main.cpp
#include <stdio.h>
#include "vectors.h"
int main(void)
{
Vector2 vector();
while(true)
{
vector += vector;//error: expression must be a modifiable value
printf("Vector counter: %d\n",vector.counter);
}
}
What i'm trying to do:
I'm trying to make my own class, and use operator overloading. But the part i can't get to work is defining the class with a header while keeping operator overloading working.
Thanks for reading my question
The following compiled in ideone: http://ideone.com/ratVVT
Changes are:
Implementation of (overload) method must specify the Class name
Implementation of (overload) method must have the same signature as the declaration (missing const).
Declaring the variable vector in main Vector2 vector(); was interpreted as a function declaration, instead of a Vector2 variable.... use Vector2 vector; or Vector2 vector=Vector2()
The code copied below.
#include <iostream>
//vectors.h
class Vector2
{
public:
Vector2();
~Vector2();
int counter;
Vector2& operator+=(const Vector2& vec);
};
//vectors.cpp
//#include "vectors.h"
Vector2::Vector2()
{
counter = 0;
}
Vector2::~Vector2()
{
}
Vector2& Vector2::operator+=(const Vector2& vec)// <---- CHANGE
{
int new_n = counter + vec.counter;
counter = new_n;
return *this;//error: this may only be used in a non-static member function.
}
//main.cpp
#include <stdio.h>
//#include "vectors.h"
int main()
{
Vector2 vector; // <---- CHANGE
while(true)
{
vector += vector;
printf("Vector counter: %d\n",vector.counter);
}
}
You are missing the class name in your method definition Vector2:: and the signature does not match because of the first parameter missing a const.
Vector2& Vector2::operator+=(const Vector2& vec)

Is it possible to overload the ostream operator for arithmetic expressions?

Is it possible to create an overload for the ostream operator that does an arithmetic operation (addition for example) and then streams out the result? The standard ostream overload that can be found all over the web can only stream from a single variable. I need something that does the following:
std::cout << x+y << std::endl;
or even more complex expressions like:
std::cout << x*y+(3*z)^2 << std::endl;
where x, y, and z are instances of a simple custom-made struct where arithmetic operations are already defined (overloaded).
EDIT:
Here is my code:
struct scalar //complex scalar data structure
{
friend scalar operator^(const scalar&, int); //integer power operator overload
friend scalar exp(const scalar&); //exponential power function
std::ostream& operator<<(std::ostream&, const scalar&)
protected:
double re;
double im;
public:
double real() {return re;} //returns the real part
double imag() {return im;} //returns the imaginary part
scalar(double _re, double _im) {re=_re;im=_im;} //constructor 1
scalar(double _re) {re=_re;im=0.0;} //constructor 2
scalar(const scalar& s): re(s.re), im(s.im) {} //copy constructor
scalar& operator=(const scalar& rhs) //assignment operator overload
{
if (&rhs==this) return *this; //checks for self-assignment
re=rhs.re; //sets real parts equal
im=rhs.im; //sets imaginary parts equal
return *this;
}
scalar& operator+=(const scalar& rhs) //compound addition-assignment operator overload
{
if (&rhs==this) return *this; //checks for self-assignment
re=re+rhs.re; //adds real parts
im=im+rhs.im; //adds imaginary parts
return *this;
}
scalar& operator*=(const scalar& rhs) //compound multiplication-assignment operator overload
{
if (&rhs==this) return *this; //checks for self-assignment
double x1=re; double x2=rhs.re; double y1=im; double y2=rhs.im;
re=x1*x2-y1*y2; //multiplies real parts
im=x1*y2+x2*y1; //multiplies imaginary parts
return *this;
}
scalar& operator-=(const scalar& rhs) //compound subtraction-assignment operator overload
{
if (&rhs==this) return *this; //checks for self-assignment
re=re-rhs.re; //adds real parts
im=im-rhs.im; //adds imaginary parts
return *this;
}
scalar& operator/=(const scalar& rhs) //compound division-assignment operator overload
{
if (&rhs==this) return *this; //checks for self-assignment
double x1=re; double x2=rhs.re; double y1=im; double y2=rhs.im;
double n;
n =pow(x2,2)+pow(y2,2);
if (n==0) throw(1);
re=(x1*x2+y1*y2)/n; //multiplies real parts
im=(x2*y1-x1*y2)/n; //multiplies imaginary parts
return *this;
}
const scalar operator+(const scalar& b) //addition operator overload
{
scalar c = *this;
c+=b;
return c;
}
const scalar operator*(const scalar& b) //addition operator overload
{
scalar c = *this;
c*=b;
return c;
}
const scalar operator-(const scalar& b) //addition operator overload
{
scalar c = *this;
c-=b;
return c;
}
const scalar operator/(const scalar& b) //addition operator overload
{
scalar c = *this;
c/=b;
return c;
}
};
scalar i(0.0,1.0);
scalar j(0.0,1.0);
std::ostream& operator<<(std::ostream& out, const scalar& s)
{
out << s.re << '+' << s.im << 'i';
return out;
}
scalar operator^(scalar a, int b) //integer power operator overload
{
double x=a.real(); double y=a.imag();
if (x==0) throw(1);
int r=sqrt(pow(x,2)+pow(y,2));
int arg=atan2(y,x);
scalar c(r*cos(arg),r*sin(arg));
return c;
}
scalar exp(const scalar& s) //exponential power function
{
double x=s.re; double y=s.im;
scalar c(exp(x)*cos(y),exp(x)*sin(y));
return c;
}
Here is my main function:
int main()
{
scalar x(3,4);
scalar y=2;
cout << x*y << endl;
return 0;
}
This is is the output it is supposed to give:
6+8i
And this is the errors it gives instead:
In function 'std::ostream& operator<<(std::ostream&, const scalar&)':|
error: passing 'const scalar' as 'this' argument of 'double scalar::real()'
discards qualifiers|
And if I remove the const as the compiler says, I will get the following error:
error: no match for 'operator<<' in 'std::cout << scalar::operator*(const scalar&)
(((const scalar&)((const scalar*)(& y))))'|
The << operator can't handle the full expression - and why should it?
You need to implement the separate operators (operator+, operator*, ...) for your struct, which take your structs as parameters, do the corresponding operation on it, and return another of your structs. And only then define a operator<< taking a single one of your structs.
How would you even think of passing in such a complex structure to the operator<<, let alone parse it in there? Implement the separate operators, and leave the parsing to the compiler.
e.g. for a simple struct only encapsulating an int, doing that with + operation would look like this:
struct mystruct
{
int value;
};
then define:
mystruct const operator+(mystruct const & a, mystruct const & b)
{
mystruct result;
result.value = a.value + b.value;
return result;
}
and
std::ostream & operator<<(std::ostream& out, mystruct const & a)
{
out << a.value;
return out;
}
then you can do:
mystruct a, b;
a.value = 1;
b.value = 2;
std::cout << a+b;
Edit: With your updated code, there's exactly one problem:
std::ostream& operator<<(std::ostream&, const scalar&)
should be
friend std::ostream& operator<<(std::ostream&, const scalar&);
i.e. you're missing friend and an ;
Though the error you show suggests some different problem (which jrok's answer would have a solution for) - that doesn't seem to result from compiling the code you show! So please get the shown code and error message in sync.
The error is because functions scalar::real and scalar::imag are not const - you can only call const member functions when you've got a reference to a constant scalar.
double real() const {return re;}
double imag() const {return im;}
Why don't you just write std::cout << (x+y) << std::endl;
and be done?
As long as your overloaded operator takes its argument by value:
ostream& operator<<(ostream&, Thing)
or constant reference:
ostream& operator<<(ostream&, const Thing&)
you can use it for any expression with type Thing.
You should put parentheses around complex expressions, to avoid surprises from operator precedence; in particular, the second expression involving ^ won't be parsed as you expect.
You'll only be restricted to a single variable (or, more accurately, an lvalue expression) if the operator requires a non-constant reference; so don't do that.
UPDATE Now we've seen the code, the main issue is the in-class definition of operator<< as a member function; it can't be a member. Perhaps you want it to be a friend, so it can access im and re; or perhaps you should remove the declaration (making it a non-member, non-friend), and just use the public interface. If you do that, you'll need to add const to real() and imag(), so they can be called on a const object. You should do that anyway.
(Looking at the reported error, it seems you've already changed it to use the public interface, but haven't declared the necessary functions const).

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).