Can we assign a integer to a object? - c++

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

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.

Can assignment operator be overloaded to return the value of a property of a class?

I wanted to return the value of a property of a class using assignment operator. I tried to fulfill this purpose. I searched a lot on the web but all of the websites I visited talked about how to overload assignment operator to do like a copy constructor of a class like this: class_t& operator=(class_t&);. Can anybody help me overload this operator to return the value of a property of a class?
This is my code:
class A_t
{
private:
int value = 0;
public:
int operator = (A_t); // I failed to overload assignment operator for this
A_t& operator = (int); // I succeeded to overload assignment operator for this
int Value();
void setValue(int);
};
A_t& A_t::operator = (int value)
{
this->setValue(value);
return *this;
}
int operator = (A_t &data)
{
return data.value;
}
int A_t::Value() { return this->value; }
void A_t::setValue(int data) { this->value = data; }
int main()
{
A_t object = 3;
int value = object; // Error: cannot convert 'A_t' to 'int' in initialization
cout << value << endl;
return 0;
}
You can’t overload operator = for this. What you can do instead is overload the implicit conversion-to-int operator inside the class:
operator int() const { return value; }
However, think carefully whether this is actually a good idea in your case. Implicit conversions should usually be avoided at all cost, because it’s very error-prone (many smart people think C++ shouldn’t allow defining custom implicit conversions at all!).
For this, you need an int operator for your class which returns the variable when being assigned to an integer. Plus the class missed the constructor required for A_t object = 3;. The corrected class looks like this,
class A_t
{
private:
int value = 0;
public:
//int operator = (A_t); <-- You dont need this.
A_t& operator = (int); // I succeeded to overload assignment operator for this
int Value();
void setValue(int);
/**
* Construct using an integer value.
*
* #param val: The value to be set.
*/
A_t(int val) : value(val) {}
/**
* int operator.
*
* #return The value stored inside.
*/
operator int() const
{
return value;
}
/**
* int& operator (optional).
*
* #return The variable stored inside.
*/
operator int& ()
{
return value;
}
};
A_t& A_t::operator = (int value)
{
this->setValue(value);
return *this;
}
int A_t::Value() { return this->value; }
void A_t::setValue(int data) { this->value = data; }
int main()
{
A_t object = 3;
int value = object; // Error: cannot convert 'A_t' to 'int' in initialization
cout << value << endl;
return 0;
}

Overload operator +

Simple question: I have a class simple_fraction and want to overload operator "+". Complilator returns error "operator + local function definition is illegal.
#pragma once
#include <iostream>
class simple_fraction {
private:
int numerator; //числитель
int denominator; //знаменатель
public:
simple_fraction(int numerator, int denominator) {
//определение основных математических операций для простой дроби
double operator+ (double val) { return number + val; } //сложение
}}
int main()
{
simple_fraction fr(2, 3);
double sum = fr + 10; //сумма
}
what is wrong with that?
You have:
simple_fraction(int numerator, int denominator) {
//определение основных математических операций для простой дроби
double operator+ (double val) { return number + val; } //сложение
}}
which makes the operator+ function a local function inside the constructor, which is not allowed. You need to finish the constructor definition before the operator+ function. And you also need to correct the operand inside the operator+
simple_fraction(int numerator, int denominator) : numerator(numerator),
denominator(denominator){}
double operator+ (double val) { return numerator + val; }
PS
That implementation of operator+ does not sound right. Perhaps you meant:
double operator+ (double val) { return 1.0*numerator/denominator + val; }

Overloading operator+ in class

Let's say I have a class Number
class Number
{
public:
int numb;
Number (int g)
{
numb = g;
}
int operator+(int h)
{
return this->numb+h;
}
};
And when I try to use my overloaded operator
cout << 3 + s; // doesn't work
cout << s + 3;
I understand why it doesn't work, but I don't know how to make it work for 3 + s
Of course, I can write operator+ with 2 arguments outside the class, but I want to have my operator overloaded in the class.
I've googled it, but didn't find any solution.
Easiest way to go: write another overload outside of your class
class Number
{
public:
int numb;
Number (int g)
{
numb = g;
}
int operator+(int h)
{
return this->numb+h;
}
};
int operator+(int h, Number& n)
{
return n.numb+h;
}
int main()
{
int s = 42;
std::cout << 3 + s;
std::cout << s + 3;
}
Live Example
This also works if your data is private (but make sure the outside function has access to those members)
class Number
{
int numb;
public:
Number (int g)
{
numb = g;
}
int operator+(int h)
{
return this->numb+h;
}
friend int operator+(int, Number&);
};
int operator+(int h, Number& n)
{
return n.numb+h;
}
Of course, I can write operator+ with 2 arguments outside the class, but I want to have my operator overloaded in the class.
This is like saying "Of course I could hammer in my nail with a hammer, but I want to use a screwdriver..."
Some other solutions suggested using both a member and a non-member, but that is redundant: if you add the non-member then you no longer need the member!
The proper way to overload operator+ is to use the non-member:
Number operator+(Number a, Number b)
{
return a.numb + b.numb;
}
Another way to write this is to use operator+= as a helper (then your class will support += too):
Number operator+(Number a, Number b)
{
return a += b;
}
with member function:
Number &operator+=(Number b)
{
numb += b.numb;
return *this;
}
You could either make operator+ return Number or int, your choice.
Just write an operator outside the class that calls the one in your class!
template<typename T> T operator+(T a, Number& n)
{
return n+a;
}

operator= in c++ (11) working direction

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;
}