I'll start from the beginning of what is in a class. A class is a collection of variables and functions that a person uses in their program. The purpose of a function is designed to allow a user to put a series of code that are related to an operation. After coding each function you can just call for those functions in the
int main()
portion of your program.
A simplified example of what you would use classes for is if you wrote a calculator program.
You might make a class that contains 3 functions
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class calc
{
private: //only accessable by members of its own class
float sum;
int x;
float mult;
float sub;
float avg;
public:
calc(); //would be where you declare your initial values and have inital input from users.
void calculations();//this could be where you put your formulas for manipulating the inputs the users does
void difference();//this just makes it so I subtract all my other values from my initial input instead of zero
void outputs();//this could be where you write your code for your outputs and have them all set up
|
*note that you do not actually put any of your statements inside the class. Like with the function
void calculations();
you do not put your
sum+=num1;
there. (Hopefully my bad grammar isn't confusing you)
now after the class portion of your code, but before your int main() function you write out the functions of your class.
Here is an example with an old calculator program of mine
1 2 3 4 5 6
|
calc::calc()
{
std::cout<<"Please Input Your Values"<<std::endl;
std::cout<<"Up To 100 Values"<<std::endl;
std::cout<<"Type 0 When Ready To Calculate"<<std::endl;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void calc::calculations()
{
for (int i=0;i<Size;i++)
{
cin>>int x;
if(x==0)
{
break;
}
sum+=x;
void difference();//this will call my difference function into my caluclation function to cut down on coding space
mult*=x;
avg = sum/i;
|
1 2 3 4 5 6 7 8 9 10 11
|
void calc::difference()
{
if (i==0)
{
sub=x;
}
else
{
sub-=x;
}
}
|
1 2 3 4 5 6 7 8 9
|
void calc::outputs()
{
std::cout<<"Sum of the values are: "<<sum<<endl;
std::cout<<"The Difference of the Values are: "<<sub<<endl;
std::cout<<"Mult equals: "<<mult<<std::endl;
std::cout<<"Minimum Value: "<<fmin<<endl;
std::cout<<"Maxmimum Value: "<<fmax<<endl;
std::cout<<"The Average is: "<<avg<<endl;
}
|
after you would do all this your main function would just look like
1 2 3 4 5 6 7 8 9 10 11
|
int main()
{
calc.objectName; //just using objectName as a reference so that code will come out properly
objectName.calculations();
objectName.outputs();
return 0;
}
|
so all that code used earlier is just condensed down to those 3 simple functions in your main portion =). Try to get the basics of writing classes where your functions don't require references or parameters. After you got that then try to implement those. GL and happy coding!