Structured programming
In structured programming, the idea of top-down, progressive refinement and modularization is adopted to decompose complex big problems into many simple small problems layer by layer.
When writing the program, use the basic control structure in 3 to construct the program. It can be said that programs basically contain sequence, selection, and loop 3 basic control structures, which are still the only control structures up to now. The program is based on the control structure as a unit, with only one entrance and one exit. Based on the control structure, the program can be read sequentially from front to back. The static description of the program is easy to correspond with the control process during execution, so each part can be understood independently. The main emphasis of structured programming is readability.
The concept and characteristics of object-oriented programming
concept
- The so-called object-oriented programming method is to make the method of analyzing, designing and implementing a system as close as possible to people’s understanding of a system. It usually includes three aspects:
- Object-oriented analysis
- Object-oriented design
- Object-oriented programming
- Object-oriented technology sees a problem as a collection of interacting things, that is, objects. Objects have two properties:
- State: Information about the object itself, also known as properties.
- Behavior: Operations on objects.
- Through the abstraction of things, find out the common attributes (static characteristics) and behavior (dynamic characteristics) of the same kind of objects, so as to get the concept of class.
- An object is a representation of a class, and a class is an abstraction of an object.
The characteristics of
- Object names, attributes, and operands are used to describe objects in C++.
- Object-oriented programming hasabstract,encapsulation,inheritanceandpolymorphismFour basic features.
- abstractAn object is an entity in a system that describes objective things. The characteristics of objects include two aspects:Properties and operations.
- Attributes are data items that describe the static characteristics of an object and can be represented by variables
- An operation is a sequence of functions that describes the dynamic characteristics of an object, also known as a method or service.
- Encapsulation: in C++, data encapsulation and information hiding are supported through user-defined classes.
- Inheritance: in C++ existing classes can be declared on the basis of a new class, an existing class of data and functions reserved, and add their own special data and functions, so as to form a new class, this is the idea of inheritance and reuse. The original class is a base class, also known as a parent or superclass. A new class is a derived class, also known as a subclass.
- Polymorphism: When different types of objects have behaviors with the same name, but the specific behaviors are implemented in different ways. Within a class or classes, you can have multiple methods with the same name, thereby becoming polymorphic. This is polymorphism through function overloading and operator overloading.
- abstractAn object is an entity in a system that describes objective things. The characteristics of objects include two aspects:Properties and operations.
A preliminary knowledge of class
The definition of a class
- Members of a class are divided by function, including member variables and member functions. Divided by access rights, including public members, private members and protected members.
- In C++ it is also possible to define functions that are not members of any class; such functions can be called global functions.
- Member functions can be defined either inside or outside the class body. If a member function is defined inside the class body, the default is inline. A member function can also be inline by declaring a function inside the class body with the inline keyword and then defining the function outside the class body.
The name of the | describe | On behalf of |
---|---|---|
Member variables | Is a class member of a class, There’s no limit to the number, Also known as data members. Member variables are declared in the same way as normal variables. |
Object representativeattribute |
A member function | Is another class member of the class, There’s no limit to the number, It is declared in the same way as normal functions. |
Represents the data contained in the class object The method of performing an operation. |
-
Identifiers are named as follows: ** IS a case-sensitive combination of letters, digits, and underscores (_). The identifiers cannot start with a number or be the same as the keywords used in the system.
-
A class is an entity with a unique identifier, which means that the class name cannot be repeated. Class definitions begin with; The part in braces is called the body of the class.
-
** The system does not allocate storage for a class when it is defined, but treats it as a template or boilerplate. In other words, a class can be thought of as a user-defined data type. Under the C++98 standard, any member declared in a class cannot be decorated with the auto, extern, and register keywords.
-
If a member function is defined outside the class body, then the class body must have the function prototype, and the function definition must be preceded by the class name ::, in the following format:
Return value Type Class name :: Member function name (argument list) {member function body}Copy the code
-
The class name is the name of the class to which the member function belongs. The symbol :: is the ** classscope operator **, indicating that the member function following it belongs to the class identified by the class name. The return value type is the type of the member function’s return value.
-
Member variables of class C cannot be defined in class C, but Pointers and references to class C can be defined.
The sample
MyDate class
class myDate {
public:
myDate(a);// constructor
myDate(int.int.int); // constructor
void setDate(int.int.int); // Set the date
void setDate(myDate); // Set the date
myDate getDate(a); // Get the date
void setYear(int); / / set in
int getMonth(a); / / set the month
void printDate(a) const; // Prints the date
private:
int year, month, day; // Member variables
};
myDate::myDate() {
year = 1970;
month = 1;
day = 1;
}
myDate::myDate(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void myDate::setDate(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void myDate::setDate(myDate date) {
year = date.year;
month = date.month;
day = date.day;
}
myDate myDate::getDate(a) {
return *this;
}
void myDate::setYear(int y) {
year = y;
}
int myDate::getMonth(a) {
return month;
}
void myDate::printDate(a) const {
cout << year << "Year" << month << "Month" << day << "Day" << endl;
}
Copy the code
Student class
class Student {
public:
Student(a);Student(string, myDate);
string _nickname;
void setStudent(string, myDate);
void setName(string);
string getName(a);
void setBirthday(myDate);
myDate getBirthday(a);
void printStudent(a) const;
private:
string _name;
myDate _birthday;
};
Student::Student() {
_name = "xxx";
_nickname = "nickname";
_birthday = myDate(1970.1.1);
}
Student::Student(string name, myDate birthday) {
_name = name;
_nickname = "nickname";
_birthday = birthday;
}
void Student::setStudent(string name, myDate birthday) {
_name = name;
_birthday = birthday;
}
void Student::setName(string name) {
_name = name;
}
string Student::getName(a) {
return _name;
}
void Student::setBirthday(myDate birthday) {
_birthday = birthday;
}
myDate Student::getBirthday(a) {
return _birthday;
}
void Student::printStudent(a) const {
cout << "Name:" << _name << ", nickname =" << _nickname << ", birthday:";
_birthday.printDate(a); cout << endl; }Copy the code
The main function
#include <iostream>
#include "myDate.hpp"
#include "Student.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
string name;
int y, m, d;
cout << "Please enter the student's name and date of birth in the order \" year month day \" << endl;
cin >> name >> y >> m >> d;
Student s = Student(a); s.setStudent(name,
myDate(y, m, d));
s.printStudent(a);return 0;
}
Copy the code
Class sample program profiling
Program structure
- A complete C++ program consists of the following parts:
- A main function that can call other functions but cannot be called. Also called a main program.
- Any number of user-defined classes and global functions
- Global description. Variable descriptions and function prototypes in addition to all function and class definitions.
- annotation
- The header file
- For large programs, classes and global functions can be divided into several program files according to the functions and relationships of the main function and each user-defined class and global function, including
.cpp
Files and.hpp
/.h
File..cpp
Files are source files,.hpp
/.h
A document is a submission document.
Definition of member variables and member functions
When implementing member functions, specify the name of the class. The general format for defining member functions outside the class is as follows:
Return value Type Class name :: Member function name (argument list) {member function body}Copy the code
There is not one member function for each object. Like ordinary functions, member functions have only one copy in memory, which can be implemented in different scopes and shared by each object in the class.
Usually, because the function body code is long, only the prototype of the member function is given inside the class body, and then the corresponding function body is given outside the class body. If the function body is defined in the class body, the system treats it as an inline function. Member functions defined in a class allow overloading.
Create the basic form of the class object
void create(a) {
// Class name Object name;
Student s;
// Class name Object name (parameter);
myDate birthday(2020.5.25);
// Class name Object name = class name (parameter);
Student s1 = Student("G.E.M.", birthday);
// Can be extended to multiple objects
Object name 1, object name 2, object name 3,... ;
Student s2, s3, s4;
// Class name Object name 1(parameter), object name 2(parameter)... ;
Student s5("Fifty", birthday).s6("Daisy", birthday);
// Class * object name = new class name;
Student *s8 = new Student;
// Class name * object name = new class name ();
Student *s9 = new Student(a);// Class name * object name = new class name (parameter);
Student *s10 = new Student("十号", birthday);
}
Copy the code
When we create an object with new, we return a pointer to the object that our class just created. All C++ allocates to Pointers is space to store pointer values, while the space taken up by objects is allocated on the heap. Objects created with new must be destroyed with DELETE.
As with basic data types, you can also declare references to objects, Pointers to objects, and arrays of objects.
void create1(a) {
Student s = Student("Guangxi forever".myDate(1999.9.9));
// Declare object references, i.e., variable aliases
Student &yonggui = s;
// Declare Pointers to objects
Student *yg = &yonggui;
// Declare an array of objects
Student students[5];
}
Copy the code
Objects of the same type can be assigned to each other. Both objects and object Pointers can be used as function arguments. The return value of a function can be an object or a pointer to an object.
Access a member of an object
void visit(a) {
Student s = Student(a);//1. The format for accessing a member variable through an object
// Object name. Member variable name
s._nickname = "Small.";
// The format for calling member functions
// The object name.
s.printStudent(a);// Name: XXX, nickname = Hachi, birthday: January 1, 1970
//2. Access a member of the object by reference
Student &sRef = s;
// Set the name
sRef.setName("Reference");
sRef.printStudent(a);// Name: quote, nickname = Hachi, date of birth: January 1, 1970
//3. Access a member of an object through a pointer
Student *sPointer = &s;
sPointer->setName("Pointer");
sPointer->_nickname = "Little needle";
sPointer->printStudent(a);// Name: pointer, nickname = needle, date of birth: January 1, 1970
}
Copy the code
The accessible scope of a class member
Access the range specifier | meaning | role |
---|---|---|
public |
public | The member of the class that it decorates Can be accessed from anywhere in the program |
private |
private | The member of the class that it decorates Can only be accessed within this class |
protected |
The protected | betweenpublic andprivate Between,The member of the class that it decorates Can be accessed in this class and subclasses |
Hidden function
The mechanism for setting private members is called hiding. One purpose of hiding is to force access to private member variables through public member functions. The advantage of this is that if you change the type and other attributes of a member variable later, you only need to change the member function. Otherwise, all statements that directly access member variables need to be modified.
Scope and visibility of identifiers
- Identifiers are one of the smallest components of a program. ** Class names, function names, variable names, constant names, and enumeration type values are all identifiers. ** These identifiers have their own scope and visibility. The scope of an identifier is the valid scope of the indicator identifier, that is, the area where it exists in the program. The visibility of an identifier refers to the area in the program where it can be used. For the same identifier, the two regions may not coincide exactly.
- The scope of identifiers in C++ is: function stereotype scope, local scope (block scope), class scope, and namespace scope.
Function prototype scope
-
The scope of a parameter when declaring a function prototype is the function prototype scope, which is the smallest scope in C++ programs. For example, we have the following function declaration:
double area(double radius); Copy the code
-
Radius identifier radius is scoped between the left and right parentheses of the function area parameter list, and cannot be referenced elsewhere in the program. Because parameters in a function declaration are valid only in the parameter list, function declarations often do not write the parameter name, but only the type of the parameter.
Local scope
The class scope
A class can be regarded as a set of named members. Member M of class X has class scope and access to M is as follows:
- If in the class
X
If no local scope identifier of the same name is declared in the member function of them
. In other words,m
It works in a function like this. - Outside of a class, expressions can be used
x.m
orX::m
To access thex
Is the classX
The object. This is the most basic way to access object members in a program. Of course, such access cannot be violatedm
Of the access modifier. - Outside the class, you can pass
ptr->m
Such an expression to access, whereptr
To point to the classX
Is a pointer to an object. Of course, such access cannot be violatedm
Of the access modifier.
Namespace scope
The general form for defining a namespace is as follows:
namespaceNamespace names {various declarations within a namespace (function declarations, class bibles,...) }Copy the code
You can directly reference the identifiers declared in the current namespace inside the namespace. To reference identifiers in other namespaces, use the following methods:
Namespace name :: Identifier nameCopy the code
For example, define a namespace as follows:
namespace SomeNs {
class SomeClass {. };someFunc(intpram) {.... }; }int main(a) {
// reference class SomeClass or function someFunc
SomeNs::SomeClass obj1;
SomeNs::someFunc(5);
return 0;
}
Copy the code
To solve this problem, C++ also provides a using statement. Using and has two forms:
usingNamespace name :: identifier name; orusing namespaceNamespace name;Copy the code
Scope hiding rules
Variables with namespace scope are also called global variables.
For identifiers declared in different scopes, the general rules for visibility are as follows:
- Identifiers are declared first and referenced later.
- Identifiers with the same name cannot be declared in the same scope. Identifiers of the same name declared in different scopes that do not contain each other do not affect each other.
- If there are two or more scopes with containment relationships, the outer layer declares an identifier, and the inner layer does not redeclare an identifier of the same name, then the outer identifier is still visible in the inner layer. If an identifier of the same name is declared on the inner layer, the outer identifier is not visible on the inner layer. In this case, the inner identifier is said to hide the outer identifier of the same name. This mechanism is called the hiding rule.