Overloaded Assignment Operator

I've written a fraction class with numerator and denominator and I want to assign with frac a = frac(n,d). My Operator doesn't work and I don't know why.
I'm grateful for any advice. Thank you very much!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 #include <iostream>
#include <cmath>

using namespace std;


class frac
{
	private:
	
	int n,d;

	public:
	void set_n(int n){n=n;}

	void set_d(int d)
	{
	 if(d!=0){d=d;}
	}

	int get_nu()const{return n;}
	int get_de()const{return d;}

	frac &operator=(const frac &a)
	{
	 int num=a.get_nu();
	 this->set_n(num);
	 int den=a.get_de();
	 this->set_d(den);
	 return *this;
	}

	frac():n(1),d(1){}
	
	frac(int n,int d):n(n),d(d){}
};

ostream &operator<<(ostream &out,const frac &a)
	{
	 out<<a.get_nu();
	 out<<"/";
	 out<<a.get_de();
	 return out;
	}


int main()
{
  frac q;
    
	q = frac(3, 2); 
  
  cout << "q = " << q <<endl;

	return 0;
The problem is in set_n and set_d. n=n assigns the parameter n to itself which leaves the member variable n unchanged.

Note that there is no need to for you to define an assignment operator because the default one will work just fine.
There is also no need for a fraction class since there is std::ratio
http://www.cplusplus.com/reference/ratio/ratio/
Thank you very much, the names were the problem :-)
Topic archived. No new replies allowed.