0
Can anyone find error in this code ??also write correct code for same
#include <iostream> using namespace std; class addition { private: int a,b,sum; public: void first_number{ cout<<"enter first number:-"; cin>>a; void second_number{ cout<<"enter second number"; cin>>b; void total{ sum=a+b; cout<<"sum of these two number is:-"; }; int main(){ int hellow; hellow.first_number(); hellow.second_number(); hellow.total(); }
4 Respuestas
+ 4
The problem in your code include:
- function definition does not declare parameters.
- you forgot to put '}' for close the function.
- not declare an object of class Addition.
- you forgot to calculate the sum and print to the screen.
Solution
#include <iostream>
using namespace std;
class Addition
{
private:
int a,b,sum;
public:
void first_number(){
cout<<"enter first number: ";
cin>>a;
}
void second_number(){
cout<<"enter second number";
cin>>b;
}
void total(){
sum=a+b;
cout<<"sum of these two number is: "<< sum <<endl;
}
};
int main(){
Addition obj;
obj.first_number();
obj.second_number();
obj.total();
}
+ 2
Phurinat Puekkham, just as a note, you removed the variable sum but still try to access it inside total(). Either add the field again or remove the statement
sum = a + b;
from the definition of total().
Also, for the sake of encapsulation, the fields a and b should remain private.
Otherwise correct explanation. :)
+ 2
Shadow Oh my bad, Thank you for correcting me.
0
Thx