Objects and classes - class features, constructors, destructors, composition of classes, forward reference declarations, enum classes, structs, unions


Object: A simulation of an object in reality, with properties and behavior.
Class: Common properties and behaviors of objects of the same class. An object is an instance of a class, and the common properties and behaviors of objects of the same class are abstracted to form a class.
The class encapsulates the data and the functions that process the data together, hides the details and provides an external interface. When compiling an object, we need to use the constructor to initialize the object. When an object is deleted, the resources occupied by the object are released through the destructor function.
When defining a class, we can also use the objects of the existing class as members of the new class for composition.
The basic characteristics of the class:
Abstract: Generalize the common properties and behaviors of objects of the same class to form a class.
Encapsulation: Encapsulate the abstracted data and code together to form a class.
Polymorphism: The same name has different functions in the program.
Inheritance: Extending existing classes to form new classes.
class Stock{//If you don't write public, the default is private
private:
std::string company;
long shares;
double share_val;
double total_val;
void set_tot(){total_val=shares*share_val;}
public://external interface
void acquire(const std::string &co,long n,double pr);
};
Object definition:
Class name Object name (Stock myStock;) To implement a class in the main function, first define an instance of the class: Stock myStock, and then call the function of the class.
Members in a class can access each other, using member names to access each other, and accessing members from outside the class use "object name·member name" to access public members.
Member functions of the class:
1. Declare the function prototype in the class;
2. Give the function body implementation outside the class and qualify it with the class name before the function name.
3. You can also give the function body directly in the class to form an inline member function.
4. Allows to declare overloaded functions and functions with default parameter values.

Inline function:
Efficiency can be improved, so don't include complex structures. How to declare an inline function:
1. The function body is placed in the class declaration
2. Put the function definition in the class, and use the inline keyword to define the function body outside the class

Constructor: Clock(int newH=0,intM=0,int newS=0);//After writing the constructor, the system will not automatically generate the default constructor. At this time, we need to manually add the constructor. function overloading.
1. Special functions in classes
2. Used to describe the initialization algorithm
Require:
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. Can have formal parameters or not
4. Can be an inline function
5. Can be overloaded
6. Can take default parameter values
The constructor is called automatically when the object is created.
Default constructor:
Clock();
Implicitly generated constructor: If the program does not generate a constructor, the compiler will automatically generate a default constructor with an empty parameter list and no initial value for data members.
Initialization list: Initialize the member list of the class, and assign the formal parameter value to the data member of the corresponding item of the class
Clock::Clock(int newH, int newM, int newS):// call the constructor with parameters
hour(newH),minute(newM),second(newS){
}
Clock::Clock():
hour(0),minute(0),second(0){//Call the constructor without parameters
}

use of constructor
Clock a1(0,0,0);//Call the constructor with parameters, which can also be written as Clock a1=Clock(0,0,0);
Clock a2;//Call the no-argument constructor

Delegate constructor: Use other constructors of the class to perform the initialization process, de-complicate the constructors with the same function body, and ensure code consistency.
Clock (int newH, int newM, int newS):
hour(newH),minute(newM),second(newS){
}
Clock():Clock(0,0,0){} //The parameterless constructor calls the parameterized constructor, passing three default initialization parameters to the parameterized constructor.

Copy constructor: Initializes a new object with an existing object a reference to the existing object is used as the parameter . If no copy constructor is manually defined, the compiler will automatically generate a default copy constructor to achieve a one-to-one correspondence between two object members. The default constructor is not sufficient when the constructor contains pointers.
When the copy constructor is called:
1. When defining an object, use another object of this class as the initial value, and copy construction occurs;
2. If the formal parameter of the function is an object of the class, when the function is called, the actual parameter object will be used to initialize the formal parameter object, and the copy will occur;
3. If the return value of the function is an object of the class, when the function execution completes and returns to the calling function, a temporary unnamed object will be initialized with the object in the return statement and passed to the calling function, and a copy construction will occur at this time.
Clock(int newH=0,int newM=0,int newS=0){}//Constructor
Clock(const Clock& p)=delete;//Instructs the compiler not to generate a default copy constructor.
example:
void fun1(point p){}//The function whose formal parameter is the point class object
Point fun2(){//The function whose return value is the Point class object
Point a;
return a;
}

Clock a;//Generate an object a
Clock b(a);//Initialize b with a, call the copy constructor for the first time
fun1(b);//Use the object as the actual parameter to call the function, the formal parameter type of the function is the object of the class, and using the formal parameter to initialize the actual parameter will also cause a copy construction
b=fun2();//The return value of the function is a class object, construct a temporary unnamed object and pass it to the caller, and call the copy construction.

A combination of classes:
1. A member of a class is an object of another class.
2. More complex abstractions can be implemented on the basis of existing abstractions.
Use the composite class constructor to pass the parameters required by the component constructor to him, and the component class constructor to initialize the component object.
Constructor design for class composition:
1. Principle: It is not only responsible for the initialization of the basic type member data in this class, but also the initialization of the object members.
#include <iostream>
using namespace std;
class Point {
public :
        int getX() { return x; }
        int getY () { return y; }
       Point( Point & p );
       Point( int a , int b );
private :
        intx ,y;
};
Point ::Point( int a , int b ) {
       x = a ;
       y = b ;
}
Point ::Point( Point & p ) { //The implementation of the copy constructor. When the parameters are passed in combination of form and real, it is passed in from the back, so myp2 is entered at the beginning.
       x = p .x;
       y = p .y;
       cout << "calling the copy constructor of Point" << endl;
}
class Line {
public :
       Line( Line & l );
        double getLen() { return len; }
       Line( Point xp1 , Point xp2 );
private :
        Point p1, p2; //p1在前先被初始化
        double len;
};
//组合类的构造函数
Line ::Line( Point xp1 , Point xp2 ) :p1( xp1 ), p2( xp2 ) { //先完成初始化列表,用形参xp1初始化当前线段的端点p1,用形参xp2初始化当前线段的端点p2。初始化顺序取决于定义的次序,在前的先被初始化
       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) { //用p1,p2初始化新的端点
       cout << "Calling the copy constructor of Line" << endl;
       len = l .len;
}
int main() {
        Point myp1(1, 1), myp2(4, 5); //建立Point类的对象
        Line line(myp1, myp2); //建立line类的对象
        Line line2(line); //利用拷贝构造函数建立一个新的对象
       cout << "the length of the line is:" ;
       cout << line.getLen() << endl;
       cout << "the length of the line2 is:" ;
       cout << line2.getLen() << endl;
       getchar();
        return 0;
}
构造组合类对象时的初始化次序:
首先对构造函数初始化列表中列出的成员(包括基本类型成员和对象成员)进行初始化, 初始化次序是成员在类体中定义的次序。
(1)成员对象构造函数调用顺序:按对象成员的定义顺序,先声明者先构造。
(2)初始化列表中为出现的成员对象, 调用默认构造函数(无形参)初始化。
处理完初始化列表后再执行构造函数的函数体。
//想要类通用,一定要记得写默认构造函数,因为当这个类的对象被用作其他类的部件时,可能组合类不写构造函数,需要部件对象有构造函数。
实现类成员函数:
void Stock::acquire( const std::string &co,long n,double pr);
类内初始值,对数据进行初始化,和函数的形参初始化类似。

前向引用声明:希望在一个类中引用另一个类的函数参数类型,第二个类再引用第一个类,两个类之间的相互引用,因为在类的引用中,定义在前的类才能被引用。如果需要在某个类的声明之前,引用该类,则应进行前向引用声明。前向引用声明只为程序引入一个标识符,但具体声明在其他地方。
两个类互相引用的例子:
class B; //前向引用声明
class A{
public:
void f(B b);//告诉参数列表B是一个类,所以在A中可以引用
};
class B{
public:
void g(A a);
};
前向引用声明注意事项:
(1)在提供一个完整的类声明之前,不能声明该类的对象,也不能在内联对象函数中使用该类。
(2)当使用前向引用声明时,只能使用被声明的符号,不能涉及类的任何细节。

结构体和类的差异:
类中默认的是private,结构体重默认是public。
使用结构体的情况:主要用来保存数据,既可以是数据成员和函数成员。

联合体
union关键词
特点:成员共用同一组内存单元,任何两个成员不会同时有效
例子:
union Mark{
char grade;
bool pass;//3个字节
int percent;//4个字节
};//成绩只有一种表现形式,内存的分配按照最大的分配

枚举类定义: 枚举型是一个集合,集合中的元素(枚举成员)是一些命名的整型常量,元素之间用逗号隔开。
语法形式:
enum class 枚举类型名:底层类型{枚举值列表};//默认的底层类型为int
例:
enum class Type:char{General,Light,Medium,Heavy};
枚举类的优势:
(1)强作用域:将其作用域限制在枚举类中,避免不同的枚举类之间的枚举值的重名问题
如使用Type的枚举值General:Type::General
(2)转换限制:枚举类对象不可以与整型隐式地互相转换
(3)可以指定底层类型

类的静态成员:被类的所有对象所共用,在类中只是进行静态数据成员说明(如:static int count)初始化在类外。












Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326282160&siteId=291194637