I'm getting the error on add, subtract, multiply and divide. I'm sure i'm missing something really simple but for the live of me i can't figure out what it is.
#include <iostream>
#include "lab 2.h"
usingnamespace std;
int main ()
{
int choice;
calculator num1, num2;
cout << "What would you like to do? add, subtract, multiply or divide? (1-4)" << endl;
cin >> choice;
if (choice == 1)
add(num1, num2);
if (choice == 2)
subtract(num1, num2);
if (choice == 3)
multiply(num1, num2);
if (choice == 4)
divide(num1, num2);
system ("pause");
return 0;
}
The header:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
class calculator
{
public:
void add(int num1, int num2);
void subtract(int num1, int num2);
void multiply(int num1, int num2);
void divide(int num1, int num2);
};
Your calculator functions reside within a class. In order to access non-static functions of a class, you need to create an object, or instance, of that class. For instance:
1 2 3 4
calculator Calculator_; // "Calculator_" is an object/instance.
// Now we can use the functions:
Calculator_.add( ..., .... );
Though, you don't actually need a class to declare your functions. Instead, what you could do (preferable) is declare your functions in the global name-space. For example:
#include <iostream>
// Global name-space starts here...
int Add( int A_, int B_ );
// Global name-space ends here...
int main( )
{
int ValueA_( 10 );
int ValueB_( 20 );
std::cout << Add( ValueA_, ValueB_ );
return( 0 );
}
// Global name-space starts here again...
int Add( int A_, int B_ )
{
return( A_ + B_ );
}
// Global name-space ends ends here for this file.
See more information here on functions: http://www.cplusplus.com/doc/tutorial/functions/ and here for classes: http://www.cplusplus.com/doc/tutorial/classes/ . In fact, see here for just about anything: http://www.cplusplus.com/doc/tutorial/
I know that their are easier ways then using a class but i need practice with how to wright one so i decided to start of with just a simple problem. But anyway i did what you suggested with making
calculator Calculator_;
but now im getting error C2664: cannot convert parameter 1 from "calculator" to "int"
so my code now looks like this:
1 2 3 4 5 6 7 8
if (choice == 1)
Calculator_.add(num1, num2);
if (choice == 2)
Calculator_.subtract(num1, num2);
if (choice == 3)
Calculator_.multiply(num1, num2);
if (choice == 4)
Calculator_.divide(num1, num2);
"num1" and "num2" are of type "calculator" can cannot be converted to an "int"; hence the error. "num1" and "num2" need to be of type "int" for your functions to work.