Chapter VII class and object

Chapter VII class and object

Import

  1. The object in the program is the simulation of the object in reality, with attribute and function / behavior;
  2. Abstract the common attributes and behaviors of the same class of objects to form a class, and the object is an instance of the class;
  3. Class encapsulates data and data processing functions, hides internal details, and provides external access interfaces;
  4. When defining an object, it can be initialized through the constructor;
  5. When deleting an object, you can release resources through the destructor;
  6. The objects of a class can be composed of objects of other classes, that is, the members of a class can be objects of other classes;

Classes and objects

  1. An object is a simulation of a real object in a program.
  2. A class is an abstraction of an object of the same class, which is a specific entity of the class.
  3. Only by defining the object of the class can the functions defined in the class be used through the object.

A design class is a design type:

  1. What is the "legal value" of this type?
  2. What functions and operators should this type have?
  3. How can new types of objects be created and destroyed?
  4. How to initialize and assign objects?
  5. Object as a parameter of a function, how to pass it by value?
  6. Who will use object members of this type?

Syntax form of class definition

class Class name
{
   public:
                     Public member (external interface)
   private:
                      Private member
   protected:
                      Protected member
};

In class initial value:

  1. You can provide an in class initial value for data members
  2. When creating an object, the initial value in the class is used to initialize the data member
  3. Members without initial values are initialized by default.

Examples of initial values in class:

class Clock {

public:

   void setTime(int newH, int newM, int newS);
   void showTime();

private:

   int hour = 0, minute = 0, second = 0;
};

Access control of class members

  1. Public type members:
    After the keyword public, it is declared that they are the interface between the class and the external. Any external function can access public type data and functions.

  2. Private type members:
    Declare after the keyword private that only functions in this class are allowed to access, and no functions outside the class can access.
    If a private member is declared immediately after the class name, the keyword private can be omitted.

  3. Protection type members:
    Similar to private, the difference is that inheritance and derivation have different effects on derived classes.

Access rights of class members

  1. Members of a class access each other
  2. Access directly using member names
  3. Out of class access: use the "object name. Member name" method to access the members of the public attribute

Member function of class

Describe the function prototype in the class;
The function body implementation can be given outside the class, and the class name can be used before the function name to limit it;
You can also directly give the function body in the class to form an inline member function;
Overloaded functions and functions with default parameter values are allowed to be declared.

inline member function

  1. In order to improve the efficiency of runtime, simpler functions can be declared as inline.
  2. Do not have complex structures (such as loop statements and switch statements) in the body of inline functions.
  3. How to declare inline member functions in a class:
  4. Put the function body in the declaration of the class.
  5. Use the inline keyword.

Application examples of class and object programs

Clocks and watches:

Class definition:
#include <iostream>
using namespace std;
class Clock{
public:
        void setTime(int newH = 0, int newM = 0, int newS = 0;
        void showTime();
private:
        int hour, minute, second;
}

Implementation of member function:
void Clock::setTime(int newH, int newM, int newS) {
         hour = newH;
         minute = newM;
         second = newS;
}
void Clock::showTime() {
   cout << hour << ":" << minute << ":" << second;
}

Use of objects:
int main() {
         Clock myClock;
         myClock.setTime(8, 30, 30);
         myClock.showTime();
         return 0;
}

Constructor

Function of constructor

When the object is created, it uses a specific value to construct the object and initialize the object to a specific initial state.

Form of constructor

  1. The function name is the same as the class name;
  2. The return value type cannot be defined, nor can there be a return statement;
  3. There can be formal parameters or no formal parameters;
  4. Can be an inline function;
  5. Can be overloaded;
  6. Can take default parameters.

Call timing of constructor

Called automatically when the object is created.

Default constructor

Constructors that do not require arguments can be called:

  1. Constructor with empty parameter table;
  2. Constructor with default values for all parameters.

Implicitly generated constructor if the constructor is defined in the program, the compiler will generate it automatically.

A default constructor:

  1. The parameter list is empty, and the initial value is not set for the data member;
  2. If the initial value of the member is defined in the class, the initial value defined in the inner class is used;
  3. If the initial value in the class is not defined, it will be initialized by default;
  4. The default initialization value of basic type data is uncertain.

"=default":
If the constructor is defined in the program, the compiler no longer implicitly generates the default constructor by default. If you still want the compiler to implicitly generate the default
Constructor, you can use: "= default".

Example:

class Clock {
     public:
          Clock() = default; //Instructs the compiler to provide a default constructor;
          Clock(int newH, int newM, int newS); //Constructor;
     private:
          int hour, minute, second;
);

Constructor instance

//Class definition

class Clock {
public:

     Clock(int newH,int newM,int newS);//Constructor
     void setTime(int newH, int newM, int newS);
     void showTime();

private:
     int hour, minute, second;
};

//Implementation of constructor:
Clock::Clock(int newH,int newM,int newS): hour(newH),minute(newM),  second(newS) {
     }

int main() {
  Clock c(0,0,0); //Call constructor automatically
  c.showTime();
     return 0;
}

Default constructor example 1:
class Clock {
public:
       Clock(int newH, int newM, int newS); //Constructor
       Clock(); //Default constructor 
       void setTime(int newH, int newM, int newS);
       void showTime();
private:
       int hour, minute, second;
};

Clock::Clock(): hour(0),minute(0),second(0) { }//Default constructor 

//The implementation of other functions is the same as before

int main() {
    Clock c1(0, 0, 0);       //Call the constructor with parameters
    Clock c2;         //Call a parameterless constructor
   ......
}

Delegating constructors

The delegate constructor uses other constructors of the class to perform the initialization process.
For example:

Clock (int newH, int newM, int newS):
hour(newH), minute(newM), second(newS) {
}
Clock() : Clock(0, 0, 0) {}

copy constructor

Copy constructor is a special constructor whose formal parameter is the object reference of this class.
The function is to initialize a new object of the same type with an existing object.

class Class name {
public :
   Class name (formal parameter);//Constructor
   Class name( const Class name &Object name);//copy constructor 
    //      ...
};
Class name::Class( const  Class name&Object name)//Implementation of copy constructor
{   Function body   }

Implicit copy constructor:

If the programmer does not declare a copy initialization constructor for the class, the compiler generates an implicit copy constructor itself.
The function of this constructor is to initialize the corresponding data member of the object to be established with the value of each data member of the object as the initial value.
"=delete":
If you do not want objects to be copied:

  1. C++98 practice: declare the copy constructor as private, and do not provide the implementation of the function.
  2. C++11 practice: use "= delete" to indicate that the compiler does not generate the default copy constructor.

Example:

class Point {   //Definition of Point class
public:
    Point(int xx=0, int yy=0) { x = xx; y = yy; }    //Constructor, inline
    Point(const Point& p) =delete;  //Indicates that the compiler does not generate a default copy constructor
private:
    int x, y; //Private data
};

There are three situations in which the copy constructor is called:

  1. When defining an object, take another object of this class as the initial value, and copy construction occurs;
  2. If the formal parameter of a function is an object of a class, when calling the function, the formal parameter object will be initialized with the actual parameter object, and a copy structure will occur;
  3. If the return value of the function is an object of a class, when the function returns to the calling function after execution, a temporary nameless object will be initialized with the object in the return statement and passed to the calling function. At this time, a copy structure occurs.
    (in this case, unnecessary copying can also be avoided by moving the structure.)

Destructor

  1. Complete some cleaning work before the object is deleted;
  2. At the end of the object's lifetime, the system will automatically call it, and then release the space to which the object belongs;
  3. If the destructor is not declared in the program, the compiler will automatically generate a default destructor whose function body is empty;
  4. Examples of constructors and destructors:
#include <iostream>
using namespace std;
class Point {     
public:
  Point(int xx,int yy);
  ~Point();
  //... Other function prototypes
private:
  int x, y;
};

Combination of classes

Concept of composition: members in a class are objects of another class. More complex abstractions can be implemented on the basis of existing abstractions.

Constructor design of class composition:
Principle: be responsible for initializing not only the basic type member data in this class, but also the object members.
Declaration form:

Class name::Class name(Formal parameters required by object members (formal parameters of members of this class)
: Object 1 (parameter), object 2 (parameter)
{
        //Other statements in function body
}

Initialization order when constructing composite class objects:

  1. First, initialize the members listed in the constructor initialization list (including basic type members and object members),
    Initialization order is the order in which members are defined in the class body.
  2. Call order of member object constructor: according to the declaration order of object members, the first declarant is constructed first.
  3. Initialize the member object that does not appear in the list and call the default constructor (i.e. parameterless) for initialization.
  4. After processing the initialization list, execute the function body of the 2 constructor.

Example of class assembler:

//LIne segment (LIne) class
#include <iostream>
#include <cmath>
using namespace std;

class Point { //Definition of Point class
public :
Point (int xx = 0, int yy = 0) {
    x = xx;
    y = yy;
}

Point(Point &p);
int getX() {return x;}
int getY() {return y;}

private: int x, int y;
}

Point::Point (Point &p) { //Implementation of copy constructor
    x = p.x;
    y = p.y;
   cout << "Calling the copy constructor of Point" << endl;
}

//Combination of classes
class Line { //Definition of Line class
pubilc: //External interface
Line (Point xp1, Point xp2);
Line(Line &l);
double getLen() {return len;}
private; ///Private data member
Point p1, p2; //Objects p1, p2 of Point class
double len;
}

//Constructor of composite class
Line::Line(Point xp1, Point xp2) : p1(xp1), p2(xp2) {
cout << "Calling constructor of Line" << endl;
double x = static_cast<double>(p1.getX() - p2.getX());
double y = static_cast<double>(p1.getY() - p2.getY());
len = sqrt(x * x + y * y);
}

Line::Line (Line &l): p1(l.p1), p2(l.p2) { //Copy constructor of composite class
cout << "Calling the copy constructor of Line" << endl;
len = l.len;
}

//Main function

int main() {
Point myp1(1, 1), myp2(4, 5); //Create an object of the Point class
Line line(myp1, myp2); //Create an object of Line class
Line line2(line); //Create a new object using the copy constructor
cout << "The length of the line is: ";
cout << line.getLen() << endl;
cout << "The length of the line2 is: ";
cout << line2.getLen() << endl;
return 0;
}

Forward reference declaration

  1. Class should be declared before use;
  2. If you need to reference a class before its declaration, you should make a forward reference declaration;
  3. The forward reference declaration only introduces an identifier for the program, but the specific declaration is elsewhere.
    Example:
class B; //Forward reference declaration
class A {
public :
     void f(B, b);
};
class B {
public:
     void f(A, a);
};

matters needing attention:

  1. Although using forward reference declaration can solve some problems, it is not omnipotent.
  2. Before providing a complete class declaration, the object of the class cannot be declared, and the object of the class cannot be used in inline member functions.
  3. When using forward reference declarations, only the declared symbols can be used, and no details of the class can be involved.
    Example:
class Fred; //Forward reference declaration
class Barney {
   Fred x; //Error: the declaration of class Fred is incomplete
};

class Fred {
   Barney y;
};

Introduction to UML

Three basic parts: 1 Things 2 Relationships 3 Diagrams
In UML, the dotted arrow indicates: dependency; Solid line and hollow triangle represent: inheritance; Solid line hollow diamond indicates: shared aggregation; Solid lines and solid diamonds indicate: composition aggregation.

structural morphology

  1. Structure is a kind of special form;
  2. The only difference from class: the default access permission of class is private, and the default access permission of structure is public;
  3. The main reason for the existence of structure: it is compatible with C language.
    When to use a structure instead of a class:
    1. Defines the type that is mainly used to save data without any operation;
  4. People are used to setting the data members of the structure as common, so it is more convenient to use the structure at this time

Definition of structure:

struct Structure name {
	 public members 
protected:
    Protected member
private:
     Private member
};

Initialization of structure:
If all data members of a structure are public members, and there is no user-defined constructor, base class and virtual function,
The variables of this structure can be given initial values in the following syntax form.

Type name variable name = {initial value of member data 1, initial value of member data 2,...};

Example: use structure to represent students' basic information

#include <iostream>
using namespace std;

struct Student {	//Student information structure
	int num;		//Student number
	string name;	//Names, string objects, will be described in detail in Chapter 6
	char sex;		//Gender
	int age;		//Age
};

int main() {
	Student stu = { 97001, "Lin Lin", 'F', 19 };
	cout << "Num:  " << stu.num << endl;
	cout << "Name: " << stu.name << endl;
	cout << "Sex:  " << stu.sex << endl;
	cout << "Age:  " << stu.age << endl;
	return 0;
}

Operation results:

Num:  97001
Name: Lin Lin
Sex:  F
Age:  19

Consortium

Declaration form:

union Name of consortium {
    public members 
protected:
    Protected member
private:
    Private member
};

characteristic:

  1. Members share the same set of memory units;
  2. No two members are valid at the same time.

Memory allocation of consortium:
Example:

union Mark {	//Consortium representing achievements
	char grade;	//Grades
	bool pass;	//Just remember whether you pass the course or not
	int percent;	//Centesimal score
};
[object Object]

Anonymous Union:
Example:

union {
  int i;
  float f;
}

This can be used in programs

i = 10;
f = 2.2;

Application example of consortium: use consortium to save performance information and output it

#include <iostream>
using namespace std;
class ExamInfo {
private:
	string name;	//Course name
	enum { GRADE, PASS, PERCENTAGE } mode;//Scoring method
	union {
		char grade;	//Grades
		bool pass;	//Just remember whether you pass the course or not
		int percent;	//Centesimal score
	};
public:
	//Three constructors are initialized with level, pass or fail, and percent respectively
	ExamInfo(string name, char grade)
		: name(name), mode(GRADE), grade(grade) { }
	ExamInfo(string name, bool pass)
		: name(name), mode(PASS), pass(pass) { }
	ExamInfo(string name, int percent)
		: name(name), mode(PERCENTAGE), percent(percent) { }
	void show();
}

void ExamInfo::show() {
	cout << name << ": ";
	switch (mode) {
	  case GRADE: cout << grade;  break;
	  case PASS: cout << (pass ? "PASS" : "FAIL"); break;
	  case PERCENTAGE: cout << percent; break;
	}
	cout << endl;
}

int main() {
	ExamInfo course1("English", 'B');
	ExamInfo course2("Calculus", true);
	ExamInfo course3("C++ Programming", 85);
	course1.show();
	course2.show();
	course3.show();
	return 0;
}

Operation results:

English: B
Calculus: PASS
C++ Programming: 85

Keywords: C++

Added by blackbeard on Sun, 06 Feb 2022 21:29:00 +0200