0

Classes

Hello gang, I'm currently trying to understand classes better and have started doing some basic excersizes. I have a problem with this simple class and I would really appriciate some help. The code: #include <iostream> #include <string> using namespace std; class Addition{ public: int x,y; int sum; int add(){sum = x + y;} }; int main(){ Addition work; cout<< "Enter your first number: "; cin>> work.x; cout<< "Enter your second number: "; cin>> work.y; cout<< work.add(); return 0; } From my point of view this is how I understand OOP, but the compiler just outputs a random number and doesn't do what i want it to do. Basically it should add 2 integers, where the addition process is being called from the class. Any suggestions? I have even tried to just write: #include <iostream> #include <string> using namespace std; class Addition{ public: int x,y; int add(x+y); }; int main(){ Addition work; cout<< "Enter your first number: "; cin>> work.x; cout<< "Enter your second number: "; cin>> work.y; cout<< work.add(); return 0; } Doesn't seem to work either.

7th Jan 2019, 4:11 PM
Dawid
Dawid - avatar
2 Respostas
+ 1
In your first version, change sum = x+y; to return x+y;.
7th Jan 2019, 4:33 PM
HonFu
HonFu - avatar
+ 1
thank you!
7th Jan 2019, 4:53 PM
Dawid
Dawid - avatar