The third week of learning: static member variables and functions

concept
  1. Adding the static keyword before the declaration is a static member variable or function
  2. There is only one static member, which is shared by all similar objects. Static members do not belong to any objects, they belong to classes!
  3. The sizeof operator does not calculate static member variables because it is not internal to the object.
  4. Static member variable functions can be accessed without going through the object
  5. Essentially global.
visit
  1. Class name: member name
  2. Object name. Member name (just a form)
  3. Pointer -> member name (just a form)
  4. Reference. Member name (just a form)
attention
  1. Static member variables must be initialized in the class file, otherwise they cannot be compiled
  2. Static member functions can only use static member variables or call static member functions!
  3. You define the constructor, and then change the static variables, but there may be some constructors that you don’t know about, and then there will be errors in the static variables.
  4. The temporary object will call the destructor when it dies. If you operate on the static variable on the destructor, an error may occur. (The solution is to write a copy constructor to counteract such uninvited guests)

eg. Four people practice relay race, please write down the speed and total time of each person

#include<iostream>
#include<string> 
using namespace std;
class athlete
{
    
    
	private:
		string name;
		double speed;	
	public:
		athlete(string n="No",double s=0):name(n),speed(s){
    
    }
		athlete(athlete& a):name(a.name),speed(a.speed){
    
    }
		void timing(){
    
    time+= speed;}
		static void show();
		~athlete();
		static double time;
		static int Member;
 } ; 
 
 double athlete::time=0;
 int athlete::Member = 4;
 void athlete::show()
 {
    
    
 	cout<<"Total time: "<<time<<endl;
 }
 athlete::~athlete() {
    
    
 	cout<<name<<" finish, spend "<<time<<" sec\n";
 	Member --;
 }
 
 int main()
 {
    
    
 	string* p;
 	double sp;
 	while(athlete::Member)  //我觉得这样子很阔以
 	{
    
    
 		cout<<"Enter name and speed:\n";
 		p = new string;
 		cin>>*p;
 		cin>>sp;
 		athlete(*p,sp).timing();	    
 		delete p;
	 }
	 athlete::show();
 }

Supplementary knowledge:

  1. Private static is private and cannot be accessed from external bai. It can only be called through static methods through du, which can prevent the modification of variables. Public static is public and can be accessed externally, and the value can be modified (if You are in a private declaration, but you are calling a member function, the compiler will tell you it is private)

Insert picture description here

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108556592