C++ function class and object initial solution 4
1. Constant member function
1. Definition: The function specified by the keyword const in the class is a constant member function
2. Format:
type specifier function name (parameter list) const;
3. Note:
(1) const is an integral part of the function type, so the keyword const should also be included in the implementation part of the function.
(2) Constant member functions cannot update the data of the object, nor can they call non-const-modified members
Functions (except static member functions, constructors)
Example:
#include<iostream>
using namespace std ;
class Simple
{ int x, y ;
public :
void setXY ( int a, int b) { x = a ; y = b ; }
void printXY() { cout << x << "," << y<< endl ; }
void constFun ( ) const//常函数
{ x ++ ; y ++ ; }//非法
};
1. When a class member is declared static, it is called a static member.
2. Static data members are shared by similar objects.
3. Static member functions cooperate with static data members.
4. Static members do not belong to a single object, but are shared by all objects of the class
5. The role of static member functions is not to communicate between objects, but to handle static data members:
Guaranteed access to static data members without relying on an object
6. Format:
Static data members are defined or declared with the keyword static in front of them
class A
{
int n;
static int s;
};
Summarize:
classname::name of static member
object name.static member name
Object pointer -> name of static member
Inside a static member function, direct access.
Example:
Static member functions to access non-static data members.
#include<iostream.h>
class small_cat{
public:
small_cat(double w){weight=w;total_weight+=w;total_number++;}
static void display(small_cat &w)
{cout<<"The small_cat weights "<<w.weight<<"kg\n";}
static void total_disp()
{cout<<total_number<<"small_cat total weight ";
cout<<total_weight<<" kg "<<endl;}
//Static member functions to access non-static data members.
private:
double weight;
static double total_weight; staticdouble total_number;
};
double small_cat::total_weight=0;double small_cat::total_number=0;
intmain()
{ small_cat w1(0.9),w2(0.8),w3(0.7);
small_cat::display(w1);small_cat::display(w2);
small_cat::display(w3);small_cat::total_disp();
return 0;}