It's a simple program what calculates area from given numbers. I'm not sure why "&" in this part isn't necessary. void get (int b, int c)
and int calc_area(int, int)
If I put ampersand signs nothing changes. By my logic code without ampersand signs shouldn't work. Why is that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
class area
{
int x=5, y=4;
public:
int calc_area(int, int) {return x*y;};
void get (int b, int c) {b=x; c=y;};
};
int main()
{
area s;
int a, b;
s.get(a,b);
int z= s.calc_area(a,b);
cout << z;
}
class Area
{
public:
Area()
{
_x = 4;
_y = 5;
}
int CalculateArea(int x, int y)
{
return x * y;
}
void Get(int x, int y) // Ampersands go here.
{
x = _x;
y = _y;
}
private:
int _x;
int _y;
};
Thanks, @Josue Molina, now I see - calc_area returns x * y , making a and b useless. My main idea was to get x and y values and then calculate area with them. I changed my code to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
class area
{
int x=5, y=4;
public:
int calc_area(int i, int j ) {return i*j;};
void get (int &b, int &c) {b=x; c=y;};
};
int main()
{
area s;
int a, b;
s.get(a,b);
int z= s.calc_area(a,b);
cout << z;
}
I know it's messy but its the first time I'm learning classes. Are there any fatal mistakes there anymore?
¿why is `calc_area()' a member function if it does not use the state of the object?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
class area
{
int x=5, y=4;
public:
int calc_area() const {return x*y;}
//void get (int &b, int &c) {b=x; c=y;}
};
int main()
{
cout << area().calc_area() <<'\n';
}
@ne555, I didn't want to make it simpler, I just wanted to test some things out. Anyways, why calc_area() returns zero in this code? When I call area s and use s instead of area() it seems to work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
class area
{
int x, y;
public:
int calc_area(){return y*x;};
void get (int b, int c) {x=b; y=c;};
};
int main()
{
int a, b;
cin >> a;
cin >> b;
area().get(a,b);
int z= area().calc_area();
cout << z;
}