addition and subtraction of two numbers using operator overloading - c++

#include<iostream>
using namespace std;
class add
{
private: int a,b;
public: add(int x=0)
{
a=x;
}
add operator+(add const &c) // sub operator-(sub const &c)
{ //{
add sum; // sub diff;
sum.a=a+c.a; // diff.a=a-c.a;
return sum; // return diff
} //}
void print()
{
cout<<"sum: "<<a;
}
};
int main()
{
add a1(10),a2(5); //sub s1(10),s2(5);
add a3=a1+a2; // sub s3=s1-s2;
a3.print(); // s3.print();
return 0;
}
Here I've written seperately but what to do if I need to do both in a single code?
I want a C++ code to perform them simultaneously

You can define any reasonable combination of:
Foo operator+(arg);
Foo operator-(arg);
Foo operator*(arg);
Foo operator/(arg);
And the arg can be another Foo or some other type entirely. For instance:
#include <iostream>
using namespace std;
class Operators {
public:
Operators() = default;
Operators(int v) : value(v) {}
Operators operator+(const Operators &other) {
return Operators{value + other.value};
}
Operators operator+(const int byValue) {
return Operators{value + byValue};
}
Operators operator-(const Operators &other) {
return Operators{value - other.value};
}
Operators operator-(const int byValue) {
return Operators{value - byValue};
}
Operators operator*(const Operators &other) {
return Operators{value * other.value};
}
Operators operator/(const Operators &other) {
return Operators{value / other.value};
}
int value = 0;
};
int main(int, char **) {
Operators first{10};
Operators second{20};
Operators result1 = first + second;
Operators result2 = first * second;
Operators result3 = first * 3;
Operators result4 = second / 2;
cout << "first + second == " << result1.value << endl;
cout << "first * second == " << result2.value << endl;
cout << "first * 3 == " << result3.value << endl;
cout << "first / 2 == " << result4.value << endl;
}
first + second == 30
first * second == 200
first * 3 == 30
first / 2 == 10
You'll see I overwrote operators that take two Operators objects, but I also wrote a few that take an integer argument, too.
I compiled and ran that with:
g++ --std=c++17 Whatever.cpp -o Whatever && Whatever

Related

error: no matching function for call to ‘ope::ope()

#include <iostream>
using namespace std;
class ope
{
private: int real, imag;
public:
ope(int r, int i){
real=r;
imag=i;
}
ope operator + (ope const &obj) //operator overloading
{ ope temp;
temp.imag = imag + obj.imag;
temp.real = real + obj.real;
return temp;
}
void show()
{
cout << "Result : " << real << " + i" << imag << endl;//print complex numbers
}
};
int main()
{
ope f1(2,5) , f2(7,6);
ope f3 = f1+f2;
f3.show();
return 0;
}
I am new in programming and I tried to use operator overloading but I got this error can anyone help me? In this code, I am trying to print complex numbers using operator overloading.
The line
ope temp;
requires a parameterless constructor (a.k.a default constructor), but ope has only a constructor that requires two parameters. You might as well use the parameterized constructor here:
ope operator + (ope const &obj) //operator overloading
{
ope temp(real + obj.real, imag + obj.imag);
return temp;
}
... or define a default constructor
class ope {
// ...
public:
ope(): real(0), imag(0) {}
// ...

How do I create a helper function that can access a private member and operatore += sign?

My question is at the bottom.
I am creating a module for a Mark to encapsulate between 0 and 100.
I have a few operator and conversion overload functions so far:
class Mark {
int mark;
public:
Mark(); //constructor
~Mark(); //deconstructor
Mark(int value); // mark is created using int value that sets the value of mark
void setEmpty(); // mark = 0
bool isValid()const; //checks if mark is valid
//type conversion
operator int() const; // mark casted to an int. result would be value of the mark or zero if mark is invalid
operator double() const; //mark casted to a double for gpa..equivalent of int value
operator char() const; // mark casted to char type...result would be grade latter value of mark
//binary member operator
Mark& operator += (int w); // int is added to the value of mark
Mark& operator = (int i); // mark is set to an integer
};
This is the main program:
This is the output:
HERE IS MY QUESTION
I am trying to add mark to an integer and return that integer and any invalid marks would not add any value to the integer. In the main program, this is the code, its the very last 2 lines.
Mark n(80), k(120);
cout << (val += n) << endl;
cout << (val += k) << endl;
and the output would be
140
140
I am not able to create this without their being errors saying that my += operator from above is ambiguous. So I am thinking that this needs to be a helper function?
Any help on how to do this?
Your implicit casting is weakening your type. It is so weak, that it has now become ambiguous. Since you allow a Mark to be automatically converted into an int, you may as well just use an int and create stand-alone functions that manipulate ints instead of Marks.
If you insist to manipulate Marks, you should create a type that has a smaller interface that enforces your invariants. I don't know what those are, but let's say that a Mark must be an int in [0, 100]. The following type (class) will ensure that you cannot create a Mark with values outside that range. Any accessory functionality is added as a stand-alone function that takes a Mark and manipulates its value with the confidence that such value will never be outside [0,100], because it is impossible for it to be outside the range.
#include <iostream>
#include <stdexcept>
class Mark {
public:
Mark(int value = 0) {
validate(value);
m_value = value;
}
int value() const { return m_value; }
void clear() { m_value = 0; }
// I don't know why you need in-place modifications, but here they are and
// they are exception safe.
Mark& operator+=(const Mark& other) {
int new_value = value() + other.value();
validate(new_value);
m_value = new_value;
return *this;
}
Mark& operator-=(const Mark& other) {
int new_value = value() - other.value();
validate(new_value);
m_value = new_value;
return *this;
}
private:
void validate(int value) const {
// place your own logic here -- the purpose is to ensure that a Mark cannot
// exist unless it is in a valid state.
if (value < 0 || value > 100) {
throw std::runtime_error("value must be in [0, 100]");
}
}
int m_value = 0;
};
double to_double(const Mark& mark) {
// replace with your own logic
return mark.value() / 100.0;
}
char to_char(const Mark& mark) {
// replace with your own logic
if (mark.value() > 0 && mark.value() < 50) {
return 'D';
} else if (mark.value() >= 50 && mark.value() <= 100) {
return 'A';
} else {
return 'X';
}
}
std::ostream& operator<<(std::ostream& os, const Mark& m) {
// replace with your own logic
return os << "Mark(" << m.value() << ") / " << to_double(m) << " / "
<< to_char(m);
}
int main() {
Mark m;
Mark n(25);
Mark k(100);
// Mark p(-10); // uncommented will throw exception
std::cout << m << "\n"
<< n << "\n"
<< k << "\n"
// << p << "\n" // uncommented will throw exception
;
}
Sample output:
$ clang++ example.cpp -std=c++2a
$ ./a.out
Mark(0) / 0 / X
Mark(25) / 0.25 / D
Mark(100) / 1 / A

Is it possible to overload an operator taking references/pointers to an abstract class as input?

I am working on a c++ programme that has to carry out differentiation by symbol of a given expression. For example, the derivative of (5x) will be ((0*x) + (5*1)) . Note that the integer coefficient is also treated as a variable or function hence, the product rule is used. Another example: (5 + (8 * x)) will evaluate to (0 + ((0*x) + (8*1))) . No further simplication is required.
The task requires that there be an abstract base class "Expression" with pure virtual methods and from it must stem derived classes such as Number, Variable etc. The goal is to read expressions of the form given above and print out their respective symbol-derivatives.
I have had some success in tackling this task without overloading any operators. Here is what I mean:
#include <iostream>
#include <string>
class Expression
{
public:
virtual Expression* diff() = 0; //Derivative Calculator
virtual void print() = 0;
virtual std::string stringget() = 0; //Prints current expression
};
//--------------------Number Class--------------------//
class Number : public Expression
{
private:
int num;
std::string snum;
public:
//Constuctors
Number(int n) : num(n), snum(std::to_string(num)) { }
Number() : num(0), snum("0") { }
// Rule of three does not apply as class does not contain pointer variables
//Differentiation function
Expression* diff()
{
num = 0;
snum = std::to_string(0);
return this;
}
void print()
{
std::cout << num << std::endl;
}
std::string stringget()
{
return snum;
}
};
//--------------------Variable Class--------------------//
class Variable : public Expression
{
private:
std::string var;
public:
//Constructors
Variable(std::string v) : var(v) { }
Variable() : var("x") { }
//Functions
Expression* diff() override
{
var = "1";
return this;
}
void print() override
{
std::cout << var << std::endl;
}
std::string stringget() override
{
return var;
}
};
//--------------------Addition/Sum Class--------------------//
class Add : public Expression
{
private:
std::string sum;
std::string plus = "+";
std::string leftpar = "(";
std::string rightpar = ")";
Expression* laddend; //left addend storage
Expression* raddend; //right addend storage
public:
//Constructors
Add(Expression* a, Expression* b)
{
sum = leftpar + (*a).stringget() + plus + (*b).stringget() + rightpar;
laddend = a;
raddend = b;
}
Add(Expression& a, Expression& b)
{
sum = leftpar + (a).stringget() + plus + (b).stringget() + rightpar;
laddend = &a;
raddend = &b;
}
//Copy Constructor
Add(const Add& src) : sum(src.sum), plus(src.plus), leftpar(src.leftpar), rightpar(src.rightpar), laddend(src.laddend), raddend(src.raddend) { }
//Assignment operator
Add& operator =( Add& src ) { sum = src.sum; return *this; }
//Destructor
~Add() { delete laddend; delete raddend; laddend = NULL; raddend = NULL;}
//
void print() override
{
std::cout << sum << std::endl;
}
//derivative calculator
Expression* diff() override
{
laddend = (*laddend).diff();
raddend = (*raddend).diff();
sum = leftpar + (*laddend).stringget() + plus + (*raddend).stringget() + rightpar;
return this;
}
//Expression getter
std::string stringget() override
{
return sum;
}
//Overload
Expression& operator +( Expression* rhs)
{
Add* res = new Add(this, rhs);
return *res;
}
};
//--------------------Product/Multiplication Class--------------------//
class Mul : public Expression
{
private:
std::string product = "(";
std::string ast = "*";
std::string plus = "+";
std::string leftpar = "(";
std::string rightpar = ")";
Expression* multiplicand; //left argument storage
Expression* multiplier; //right argument storage
public:
//Constructors
Mul(Expression* a, Expression* b)
{
product = product + (*a).stringget() + ast + (*b).stringget() + rightpar;
multiplicand = a;
multiplier = b;
}
void print() override
{
std::cout << product << std::endl;
}
Expression* diff() override
{
std::string lvar = (*multiplicand).stringget(); //before differentiation
std::string rvar = (*multiplier).stringget(); //before differentiation
multiplicand = (*multiplicand).diff();
multiplier = (*multiplier).diff();
product = leftpar + leftpar + (*multiplicand).stringget() + ast + rvar + rightpar + plus + leftpar + lvar + ast + (*multiplier).stringget() + rightpar + rightpar;
return this;
}
std::string stringget() override
{
return product;
}
//Overload
Expression& operator *( Expression* rhs)
{
Mul* res = new Mul(this, rhs);
return *res;
}
};
int main()
{
Expression* test = new Mul(new Number(6), new Variable("x"));
std::cout << "Current Expression: " << test->stringget() << std::endl;
Expression* test2 = test->diff();
std::cout << "Differentiated Expression: " << test2->stringget() << std::endl;
Add x(test, test2);
// x = test + test2 * test;
delete test;
return 0;
}
Which successfully compiles with the following output:
Current Expression: (6*x)
Differentiated Expression: ((0*x)+(6*1))
Now, the expression (6*x) was created by means of the line
Expression* test = new Mul(new Number(6), new Variable("x"));
But since my goal is to read expressions of the form (6*x) and even more complex expressions e.g (((4*x)+(x*x))-x) and then interpret them and finally differentiate, the only way is to overload the operators. This is where I'm getting problems.
The Problems
As you have might have noticed in the code, I have overloaded the addition and multiplication operators. However, when I try to run code such as
x = test + test2 * test1;
(This line is commented out in the provided code above) I get an error. Moreover, even with just one operator, for instance,
test = test + test2;
I get the error
error: invalid operands of types 'Expression*' and 'Expression*' to binary 'operator+'|
or
error: invalid operands of types 'Expression*' and 'Expression*' to binary 'operator+'|
This doesn't make sense to me since the parameter types coincide.
What Else Have I tried?
I've tried to pass the parameters by reference, as well as by const reference but still the same result. I also tried to write the operator overload description as a non-member function but that gives the error
must have an argument of class or enumerated type
I have also tried changing the return types from Expression& to Expression* and making the necessary subsequent edits but the errors are the same. I've even tried to implement the rule of threes for all the classes - even though it is not necessary - but the result is the same.
I'd appreciate any help on where I am missing it.

Operator overloading with multiple parameters and symbol

I have a class:
class taphop
{
public:
taphop();
~taphop();
taphop(const list&);
taphop& operator=(const taphop&);
taphop operator+(const int&);
taphop operator+(const taphop&);
};
In main, I can't using multiple parameters:
main()
{
taphop lmc=lmc+2+5+3+2; // Error;
lmc=lmc+3+5+2; // Error;
int a=a+1+2+4+5; // Not error;
a=a+1+2+4+5; // Not error;
return 0;
}
One thing for sure. Below is undefined.
taphop lmc=lmc+2+5+3+2;
As operator+ would be called on the carcass of supposed-to-be-fully-constructed object in expression
lmc+2+5+3+2
In addition to using lmc to initialize lmc, you just need to read the error messages the compiler is giving you. Here is my take on what you might be trying to do:
class taphop
{
int value;
public:
taphop(const int x = 0) :value(x) {} // default value of 0
~taphop() {}
int getvalue() const { return value; }
taphop& operator=(const taphop &r) { value = r.value; return *this; }
taphop operator+(const int x) { return taphop(value + x); }
taphop operator+(const taphop &r) { return taphop(value + r.value); }
};
int main()
{
taphop lmc = taphop(0) + 2 + 5 + 3 + 2;
std::cout << lmc.getvalue() << std::endl; // prints 12
lmc = lmc + 3 + 5 + 2;
std::cout << lmc.getvalue() << std::endl; // prints 22
return 0;
}

Creating an IntegerNumber class for a homework assignment in C++ to sum large integers as strings exceeding long range

So I am creating an IntegerNumber class that needs to be able to output an addition of integers that are about 26 digits long, for example : -12345678954688709764347890 is stored into B which is a the type IntegerNumber. A,B,C, and D are all type IntegerNumber. I don't have a problem assigning the values of each to each other like A = B or B = C using an operator= function. Later in the main code, one of the requirements is to be able to output the sum of numbers like D = A + B or even do a comparison of A < B.
I wouldn't have trouble doing this if these numbers were within the long or int range of numbers. I am having trouble figuring out how to do the addition of -12345678954688709764347890 + 5678954688709764347890 when these values are strings. What would be the best way to convert these into a type where it could be added or even compared ( A < B)?
Here is what I have so far:
#include <iostream>
#include <cstring>
using namespace std;
class IntegerNumber
{
friend ostream& operator<<(ostream &, const IntegerNumber&);
friend IntegerNumber operator+(const IntegerNumber&, const IntegerNumber&);
friend bool operator<(const IntegerNumber&, const IntegerNumber&);
friend bool operator==(const IntegerNumber&, const IntegerNumber&);
friend bool operator!=(const IntegerNumber&, const IntegerNumber&);
private:
char *intnum;
public:
IntegerNumber(); //default constructor
IntegerNumber(const char *); //constructor with C-string argument
IntegerNumber(const IntegerNumber &); //copy constructor
~IntegerNumber(); //destructor
IntegerNumber& operator=(const IntegerNumber &rhsObject); //assignment operator
int Length(); //returns length of string
};
void main() {
IntegerNumber A; // IntegerNumber object is created and A contains the integer 0
IntegerNumber B("-12345678954688709764347890"); // IntegerNumber object B is created and B contains the negative number shown within the quotes " "
IntegerNumber C = "5678954688709764347890"; // IntegerNumber object C
//is created and C contains the positive number shown within the quotes " "
IntegerNumber D(B); // IntegerNumber object D is created and D contains
// the number that B contains
A = B; // assigns the value of A to that of B
cout << A << endl; // output to screen the integer in A
B = C; // assigns the value of B to that of C
cout << A << endl; // output to screen the integer in A
// value of A must be same as before.
cout << D << endl; // output to screen the integer in D
// value of D must be same as before.
cout << B << endl; // output to screen the integer in B
// value of B must be same as that of C
D = A + B;
cout << D << endl; // output the sum of the numbers A and B
if ( A < B ) {
C = A + B;
cout << C << endl; // output the sum of A and B
}
else {
A = B + C;
cout << A << endl; // output the sum of B and C
}
if (A == B || C != D)
cout << A << " " << D << endl; // output values of A and D
}
IntegerNumber::IntegerNumber() {
intnum = new char[2];
intnum = "0";
}
IntegerNumber::IntegerNumber(const char *str) {
intnum = new char[strlen(str) +1];
strcpy(intnum, str);
}
IntegerNumber::IntegerNumber(const IntegerNumber &ob) {
intnum = new char[strlen(ob.intnum) +1];
strcpy(intnum, ob.intnum);
}
IntegerNumber::~IntegerNumber() {
delete [] intnum;
}
IntegerNumber& IntegerNumber::operator=(const IntegerNumber &ob) {
if (this != &ob) {
delete [] intnum;
intnum = new char[strlen(ob.intnum) +1];
strcpy(intnum, ob.intnum);
}
return *this;
}
int IntegerNumber::Length() {
return strlen(intnum);
}
ostream& operator<<(ostream &out, const IntegerNumber &ob) {
out << ob.intnum;
return out;
}
IntegerNumber operator+(const IntegerNumber &lhs, const IntegerNumber &rhs) {
int strLength = strlen(lhs.intnum) + strlen(rhs.intnum) +1;
char *tmpStr = new char[strLength];
strcpy(tmpStr, lhs.intnum);
strcat(tmpStr, rhs.intnum);
IntegerNumber retStr(tmpStr);
delete [] tmpStr;
return retStr;
}
bool operator==(const IntegerNumber& lhs, const IntegerNumber& rhs) {
return (strcmp(lhs.intnum, rhs.intnum) == 0);
}
bool operator!=(const IntegerNumber& lhs, const IntegerNumber& rhs) {
return (strcmp(lhs.intnum, rhs.intnum) != 0);
}
bool operator<(const IntegerNumber& lhs, const IntegerNumber& rhs) {
return (strcmp(lhs.intnum, rhs.intnum) < 0);
}
For some reason, I'm having warnings for strcpy: Warning 4 warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\users\danny\documents\visual studio 2010\projects\hw6\hw6\hw6.cpp 106 1 HW6
And also strcat with the same error, I tried changing to strcpy_s and strcat_s but I get an error saying: 6 IntelliSense: no instance of overloaded function "strcpy_s" matches the argument list c:\users\danny\documents\visual studio 2010\projects\hw6\hw6\hw6.cpp 89 3 HW6
Have a field of type std::vector<char> in your class, and store all the digits of the big number, in it and then you can sum the corresponding digits of the vectors in operator+() (just like you did in school) and return the result.
class IntegerNumber
{
//make sure that m_digits contains only digit: digit means, 0 to 9.
//when you add 9 plus 4, it becomes 14, but you don't put in into m_digits,
//rather you just put 3 (unit digit of 13), the 1 goes in the second round of sum!
std::vector<char> m_digits;
public:
IntegerNumber();
IntegerNumber(const std::string &number)
{
//parse the string 'number' and populate the m_digits;
}
IntegerNumber operator+(const IntegerNumber & number);
{
IntegerNumber result;
//sum all the corresponding digits of number.m_digits and this->m_digits
//and store in result.m_digits;
return result;
}
//...
};
EDIT:
By the way, here is how the start should look like : http://www.ideone.com/Yb5Nn