1. Composition of class
Class class name{
Public: / / public member
Function 1;
Variable 1
......
Private: / / private member
Function 2;
Variable 2
......
};
#include <iostream>
using namespace std;class score{
public:
inline void setscore(int m,int f);
inline void showscore();
private:
int mid_exam;//You cannot assign a value to a data member in a class declarationint mid_exam=90;
int fin_exam;
};inline void score::setscore(int m,int f)
{
mid_exam=m;
fin_exam=f;
}inline void score::showscore()
{
cout<<"Interim results:"<<mid_exam<<"\n The final grade is:"<<fin_exam<<"\n General evaluation result:"
<<(int)(0.3*mid_exam+0.7*fin_exam)
<<endl;
}int main(int argc, char** argv)
{
score a,*ptr;//
ptr=&a;
a.setscore(90,80);
a.showscore();
ptr->setscore(90,85);
ptr->showscore();
a.showscore();
return 0;
}
2. Constructor and destructor of class
1 > constructors are mainly used to allocate space for objects; initialization.
Note: the name must be the same as the class name. You can have any type of parameter, but you cannot have a return value.
It does not need to be called by the user, but is executed automatically when the object is created.
Data members are generally private members.
Parameter list is initialized in the order in which they are declared in the class, regardless of their order in the member initialization list
#include <iostream>
using namespace std;class score{
public:
score(int m,int f);
inline void showscore();
private:
int mid_exam;
int fin_exam;
};
score::score(int m,int f)
{
cout<<"Constructor in use\n";
mid_exam=m;
fin_exam=f;
}//score::score(int m,int f):mid_exam(m),fin_exam(n)parameter list
//{function body (can be empty, but must have braces)}
inline void score::showscore()
{
cout<<"Interim results:"<<mid_exam<<"\n The final grade is:"<<fin_exam<<"\n General evaluation result:"
<<(int)(0.3*mid_exam+0.7*fin_exam)
<<endl;
}int main(int argc, char** argv)
{
score a(90,85);
a.showscore();
return 0;
}
2 > destructor
Some cleanup work when an object is undone, such as freeing the memory space allocated to the object.
Be careful:
Destructors have no return type, no arguments, and cannot be overloaded. There can only be one destructor in a class.
When the object is undone, the compiler automatically calls the destructor.
For most classes, the default destructor is sufficient. But if there is new, the destructor must be defined for delete release.
3>
When using the parameterless constructor, define the type name object () / / without parentheses, parentheses declare a function