operator= in c++ (11) working direction - c++

I'm doing a Little rational class for my Project and I overload all aritmethic operators. Well, when I try to overload operator= I have a Little and now I don't know if is my problem (i don't know how it Works) or problem of my wroten code (i wrote it bad) here's the code:
class rational{
public:
double& operator=(double& d){
d= this->num/this->den;
return d;
}
double& operator=(rational& r){
double d= r.num/r.den;
return d;
}
double& operator=(){
double d= this->num/this->den;
return d;
}
}
Ok, what's wrong? what's right? (i think that all is wrong haha)
My goal is do that:
int main(){
rational r(4, 5);
double d= r;
}
Can I do it? if yes, how?

You don't want an assignment operator for this purpose - you should instead overload a conversion operator; e.g.
class rational {
private:
int num;
int den;
public:
// ...
operator double() { return double(num) / double(den); }
};
This will allow
rational r(4, 5);
double d = double(r); // d = 0.8
The assignment operators should be used for changing the state of an existing object, if that's something you want to allow. You probably would not want to allow assignment of a double to a rational there is no unambiguous meaning for such an operation. However, you might want to provide helpers for assigning an int, say, in addition to the usual one for assigning another rational:
rational &operator=(const rational &rhs)
{
num = rhs.num;
den = rhs.den;
return *this;
}
rational &operator=(int rhs)
{
num = rhs;
den = 1;
return *this;
}

Here I think a user-defined conversion operator would be more appropriate.
class rational {
public:
rational( int iNum, int iDen ) : num( iNum ), den( iDen ) {}
// ...
operator double() { return (double)num / (double)den; }
private:
int num;
int den;
};
int main()
{
rational r( 1, 2 );
double n = r;
std::cout << r << std::endl; // output 0.5
return 0;
}
Here is a little live example to illustrate this : http://ideone.com/I0Oj66
About the copy assignment operator= :
A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T.
The operator= is used to change an existing object.
You can use it for example to copy the state of another object :
rational &operator=( const rational &rhs )
{
num = rhs.num;
den = rhs.den;
return *this;
}

Related

How to make a variable in a struct variable that is not inputted but set based on previous variables' values

I am making a program which inputs fractions and puts them in order. I used struct to define a fraction type. I think I am making a type that initializing 2 variables(the numerator and the denominator of the fraction) and initializing the double type variable called value to a / b in this code:
struct fraction {
int a; // numerator
int b; // denominator
double value = a / b; // floating point value of fraction
bool operator > (const fraction &a) {
fraction ans;
return ans.value > a.value;
}
bool operator < (const fraction &a) {
fraction ans;
return ans.value < a.value;
}
};
int main() {
//---------logging-------
fraction ratio = {1,2};
cout << ratio.value;
//-----------------------
// outputs 0
// other things down here that is not included
}
but apparently, that is not the case because I also need to initialize value. I figured out why, but the problem is, how can I make the variable without initializing it at the creation of the fraction? Thanks!
How can I make the variable without initializing it at the creation of the fraction?
One could just write a member function double value() calculating and returning the floating-point value of the fraction, but first there are some issues in the posted code that need to be addressed (and may actually solve OP's problem).
The only in-class member variable initialization shown isn't correct.
double value = a / b; // floating point value of fraction
Beeing both a and b variables of type int, a / b is an integer division, yielding an int result that is only after assigned to a double variable. In OP's example, int(1)/int(2) == int(0).
To produce the expected value, we need to explicitly convert at least one of the terms into a double:
double value = static_cast<double>(a) / b;
Both the comparison operators are wrong.
bool operator > (const fraction &a) {
fraction ans; // This is a LOCAL, UNINITIALIZED varible.
return ans.value > a.value; // The result is meaningless.
}
The following snippet shows a possible implementation where value is calculated and not stored (which isn't necessary a good idea).
#include <iostream>
#include <numeric>
class fraction
{
int numerator_{};
int denominator_{1};
public:
fraction() = default;
fraction(int num, int den)
: numerator_{num}, denominator_{den}
{
if (auto divisor = std::gcd(num, den); divisor != 1)
{
numerator_ /= divisor;
denominator_ /= divisor;
}
}
bool operator > (fraction const& a) const noexcept {
return value() > a.value();
}
bool operator < (fraction const& a) const noexcept {
return value() < a.value();
}
auto numerator() const noexcept {
return numerator_;
}
auto denominator() const noexcept {
return denominator_;
}
double value() const noexcept {
return static_cast<double>(numerator_) / denominator_;
}
};
I think there are two solutions, either you initialize a and b with 0, or you compute a/b each time you need it.
...or you could write an exception like:
int a;
int b;
double val;
try() { val = a/b; }
catch(...){ val = 0; }
I don't think that's good tho because it's always gong to catch.

Why does this C++ snippet assigning a value to an rvalue compile?

I was reading through the third edition of Effective C++ and I was surprised that a snippet on page 18 compiles. Here is a snippet inspired from that (compiler explorer link):
struct Rational {
Rational(int numer, int denom): numer(numer), denom(denom) {}
int numer, denom;
};
Rational operator*(const Rational& lhs, const Rational& rhs) {
return Rational(lhs.numer * rhs.numer, lhs.denom * rhs.denom);
}
int main() {
Rational a(1,2), b(3,4), c(5,6);
a*b = c;
}
From my understanding, a*b is an r-value, and hence have no location in memory. How is it possible that an assignment operator can be called on an r-value?
a*b = c; calls the assignment operator on the Rational returned by a * b. The assignment operator generated is the same as if the following were defined:
Rational& Rational::operator=(const Rational&) = default;
There is no reason why this shouldn't be callable on a temporary Rational. You can also do:
Rational{1,2} = c;
If you wanted to force the assignment operator to be callable only on lvalues, you could declare it like this, with a & qualifier at the end:
Rational& operator=(const Rational&) &;
"a*b is an r-value, and hence have no location in memory" it is not quite right.
I add prints. The comments are the prints for each line of code
#include <iostream>
using namespace std;
struct Rational {
Rational(int numer, int denom) : numer(numer), denom(denom) {
cout << "object init with parameters\n";
}
Rational(const Rational& r)
{
this->denom = r.denom;
this->numer = r.numer;
cout << "object init with Rational\n";
}
~Rational() {
cout << "object destroy\n";
}
int numer, denom;
};
Rational operator*(const Rational& lhs, const Rational& rhs) {
cout << "operator*\n";
return Rational(lhs.numer * rhs.numer, lhs.denom * rhs.denom);
}
int main() {
Rational a(1, 2), b(3, 4), c(5, 6); // 3x object init with parameters
cout << "after a, b, c\n"; // after a, b, c
Rational d = a * b = c; // operator*, object init with parameters, object init with Rational, object destroy
cout << "end\n"; // end
// 4x object destroy
}
In the line Rational d = a * b = c; d is equal to c. This line call operator* function, that call the object init with parameters constructor. After that c object is copied to d object by calling copy constructor.
If you write the line: Rational d = a = c; // d == c // print only: object init with Rational the compiler assign the d object only to the last assign (object c)
Rational operator*(const Rational& lhs, const Rational& rhs) {
cout << "operator*\n";
return Rational(lhs.numer * rhs.numer, lhs.denom * rhs.denom);
}
operator *() returns an object of type Rational and that is the l value.

Can we assign a integer to a object?

I just wanted to know can we assign a integer value to a object directly. Here I just want to assign a rational value(22/7) to object x;
#include<iostream>
class rational {
private:
int num = 22, den = 7;
public:
void assign(rational x) {
x = num / den;
}
};
int main() {
rational x;
x.assign(x);
return 0;
}
However doing so gives an error of
no operator "=" matches these operands -- operand types are: rational = int
You can write a converting constructor and an assignment operator:
class rational
{
public:
rational (int val)
{
// initialize as you want
}
rational& operator= (int val)
{
// Assign as you want
return *this
}
}
But it's not at all clear what you're trying to do here. There are other problems:
Your class contains a pair of ints, not a single int
x.assign(x) looks like an attempt to assign x into itself
assign will have no lasting effect on its parameter, since it's not passed by value

How can I generate and return a result in one expression?

I have a class similar to this:
class Frac
{
int numer;
int denom;
public:
Frac &simplify();
Frac(int &&num, int &&den) : numer { num }, denom { den }
{
simplify();
}
Frac operator*(const int &rhs)
{
Frac result = { numer * rhs, denom };
return result.simplify();
}
}
However, I don't like using the intermediate result when overloading *.
Ideally, I'd like to do something like this:
Frac operator*(const int &rhs)
{
return { numer * rhs, denom }.simplify();
}
but that doesn't work; it constructs an std::initializer_list<int> instead of a Frac and you can't call the member function. In C I would be able to do this with a compound literal but those are not available in standard C++.
How can I generate and return a result in one expression?
Since you are already calling simplify() in the constructor, all you need to call is the constructor by itself, and return the object it creates:
Frac operator*(const int &rhs)
{
return Frac(numer * rhs, denom);
}
If you decide later on to update the constructor to no longer call simplify(), you can still call simplify() explicitly on the object that is created by calling the constructor:
Frac operator*(const int &rhs)
{
return Frac(numer * rhs, denom).simplify();
}

Rational class and Move Semantics not working

I have tried to add more features to already given class(the answer of #Aak) in the problem: How to output fraction instead of decimal number?
for printing fractions in numerator / denominator .
First of all, the given code was not working without any change in the code. Then I made it working after making some changes. However, my implementation gives me a wrong output.
for example:
input: A = 3;
B = 3;
Output: 9/1
9
instead of: 1
here is the complete implementation:
#include <iostream>
/********************** Rational class **********************************/
class Rational
{
private:
int m_numerator, m_denominator;
private:
inline void simplificate()
{
int commondivisor = 1;
for(int i=2;i<= std::min(abs(m_numerator), abs(m_denominator));i++)
if( m_numerator%i == 0 && m_denominator%i == 0 )
commondivisor = i;
m_numerator /= commondivisor;
m_denominator /= commondivisor;
}
public:
Rational() // Defualt
:m_numerator(1), m_denominator(1)
{}
Rational(const int& num, const int& den=1) // Parameterized
:m_numerator(num), m_denominator(den)
{}
Rational(const Rational& other) // Copy
:m_numerator(other.m_numerator), m_denominator(other.m_denominator)
{}
/*Rational(Rational&& other) // Move
:m_numerator(other.m_numerator), m_denominator(other.m_denominator)
{}*/
~Rational(){}
Rational& operator/ (const int& divisor)
{
m_denominator *= divisor;
simplificate();
return *this;
}
Rational& operator/ (const Rational &divisor)
{
m_numerator *= divisor.m_numerator;
m_denominator *= divisor.m_denominator;
simplificate();
return *this;
}
const double getrealformat()const
{
return static_cast<double>(m_numerator)/
static_cast<double>(m_denominator);
}
friend double operator/ (Rational& obj, const int& divisor);
friend void printRational(Rational& obj, const int& A, const int& B);
friend void printRational(Rational& obj, const int&& A, const int&& B);
};
/************************** Friend functions ********************************/
double operator/ (Rational& obj, const int& divisor)
{
obj.m_denominator *= divisor;
obj.simplificate();
return obj.getrealformat();
}
void printRational(Rational& obj, const int& A, const int& B) // lvalue
{
Rational r1(A), r2(B);
obj = r1/r2;
std::cout<<obj.m_numerator<<'/'<<obj.m_denominator<<std::endl;
std::cout<<obj.getrealformat()<<std::endl;
}
void printRational(Rational& obj, const int&& A, const int&& B) // rvalue
{
Rational r1(A), r2(B);
obj = r1/r2;
std::cout<<obj.m_numerator<<'/'<<obj.m_denominator<<std::endl;
std::cout<<obj.getrealformat()<<std::endl;
}
/*****************************************************************************/
int main()
{
Rational obj;
printRational(obj, 3,3);
return 0;
}
Question - 1: the logic looks fine, but I don't know why I am getting the wrong answer. Can anybody find the problem?
Question - 2: I have written "Move" constructor for the class, which you can find in the commented section. However, I could not use it because of following error:
D:\Programming\C++\CPP Programs\Class - Fractions\Class - Fractions.cpp|70|error: use of deleted function 'Rational& Rational::operator=(const Rational&)'|
D:\Programming\C++\CPP Programs\Class - Fractions\Class - Fractions.cpp|77|error: use of deleted function 'Rational& Rational::operator=(const Rational&)'|
(whenever it has been called the moved object/instance is destroyed, to my knowledge.)
can anybody help me to implement the Move constructor for this class?
Look your operator/()
Rational& operator/ (const Rational &divisor)
{
m_numerator *= divisor.m_numerator;
m_denominator *= divisor.m_denominator;
simplificate();
return *this;
}
This code is correct for operator*(), not for operator/().
Maybe
m_numerator *= divisor.m_denominator;
m_denominator *= divisor.m_numerator;
But is worse that you're operator/() modify the object.
Your code (corrected switching numerator and denominator) should be correct for operator/=(), not for operator/() that should return a new object.
I suggest something as follows
Rational& operator/= (const Rational &divisor)
{
m_numerator *= divisor.m_denominator;
m_denominator *= divisor.m_numerator;
simplificate();
return *this;
}
friend Rational operator/ (Rational A, Rational const & B);
and, outside the class,
Rational operator/ (Rational A, Rational const & B)
{ return A/=B; }
Regarding question 2 ("I have written "Move" constructor for the class, [...]However, I could not use it because of following error"), you can see in this page that
A implicitly-declared copy assignment operator for class T is defined as deleted if any of the following is true:
T has a user-declared move constructor;
T has a user-declared move assignment operator.
So, when you define the move contructor, you delete the implicit copy operator.
You can solve the problem adding
Rational & operator= (Rational const &) = default;
reactivating the implicit copy constructor