that little thing in class

kind

Basic introduction to the class

class is the keyword to define the class, ClassName is the name of the class, and {} is the body of the class. Note that the semicolon after the end of the class definition cannot be omitted. The contents of the class body are called members of the class: variables in the class are called attributes or member variables of the class; functions in the class are called methods or member functions of the class.

class className
{
    
    
// 类体:由成员函数和成员变量组成
};  // 一定要注意后面的分号

The class member definition can be directly defined inside the class (both declaration and definition are placed in the class), and it can also be declared in the class and directly defined outside the class. However, when the declaration is separated from the definition, it is necessary to consider the definition of the class name. Specifying a class name is specifying a scope.

class MyClass
{
    
    
	//直接定义
	int add(int a, int b)
	{
    
    
		return a + b;
	}
};
//
class MyClass
{
    
    
	//声明
	int add(int a, int b);
	
};
//定义
 int MyClass:: add(int a, int b)
{
    
    
	return a + b;
}

Because c++ itself is compatible with the C language, it can be regarded as a relatively large structure for a class. Since functions cannot be defined in the structure, functions can be defined in the class. After the structure is defined, the internal members of the structure can be accessed directly. However, when we define a class, an error will be reported when directly accessing its class functions or members.
insert image description here
This involves permission issues. C++ uses the structure itself to define members for better protection, so the internal members of the default class are private. Cannot be used externally. Therefore, when using classes for definition, you need to set permissions yourself. Common permissions are private (private), protect (protected), and public (public). It is safe to use limited members of keywords. Generally, it is more common to use private and public together. The members of the structure struct are public. For the consideration of protection permissions, the inheritance of base classes and derived classes will generally consider the issue of permissions after inheritance. Usually use is generally not considered.

class instantiation

A class is an abstraction of a class of objects, and the generalization is relatively broad. Common classes include the date class, and the date class object will realize the basic calculation of the date. Instantiation is instantiation from a class to a specific object. A class can be said to be like a design drawing, and an object is like an object designed according to a class. The instantiated object occupies the actual physical space and stores the class member variables. The class size needs to be calculated.

class memery
{
    
    
public:
int add(int a, int b)
	{
    
    
		return a + b;
	}
private:
	int* _a;
	int _b;
};

int main()
{
    
    


	memery M;
	cout << sizeof(memery) << endl;
	return 0;
}

In the x86 environment, the running result is 8. You can see the class members, there is a pointer and an int type, and a function body. It can be guessed that the member functions of the class are not considered when calculating the size. Then after deleting the member function, it is still 8. Does not affect class size. So it can be shown that the member function is not actually in the class. It is stored in the code section. The empty class size is 1 . This 1 is to mark that it has appeared and is used to occupy the address.
insert image description here

When accessing the same code for different objects, the compiler gives each object a this pointer in order to distinguish the objects. But it won't be used when we use it, because the compiler will call it by itself. The C++ compiler adds a hidden pointer parameter to each "non-static member function", so that the pointer points to the current object (the object that calls the function when the function is running), and all "member variable" operations in the function body, All are accessed through this pointer. It's just that all operations are transparent to the user, that is, the user does not need to pass it, and the compiler completes it automatically.

The 6 default member functions of the class

If there are no members in a class, it is simply called an empty class.
Is there really nothing in the empty class? No, when any class does not write anything, the compiler will automatically generate the following 6 default member functions.

Default member function: The member function generated by the compiler without explicit implementation by the user is called the default member function.

insert image description here

Constructor

The constructor is a special member function with the same name as the class name, which is automatically called by the compiler when creating a class type object to ensure that each data member has a suitable initial value, and is called only once in the entire life cycle of the object .

Simply put, for class member initialization, an initialization list is built to initialize data. For example, the stack commonly used in data structures will forget to initialize if we are not careful when we use it. An exception error will appear when using the stack later. So the constructor will be directly used by the compiler,

 class Date
 {
    
    
  public:
 /*
 // 如果用户显式定义了构造函数,编译器将不再生成
 Date(int year, int month, int day)
 {
 _year = year;
 _month = month;
 _day = day;
 }
 */
 
 void Print()
 {
    
    
 cout << _year << "-" << _month << "-" << _day << endl;
 }
  
  private:
 int _year;
 int _month;
 int _day;
 };

But random values ​​will appear after the above code runs. That is to say, built-in types will not be processed, and no-argument constructors will be called for custom types. So the default value can be given when the built-in type is defined. The default is not initialization. It's like going to dinner, you are ready to eat fried rice with eggs, but someone else invites you to eat a delicious dish of mountains and seas.

总结:
1. 函数名与类名相同。
2. 无返回值。
3. 对象实例化时编译器自动调用对应的构造函数。
4. 构造函数可以重载。

destructor

Destructor: Contrary to the function of the constructor, the destructor does not complete the destruction of the object itself, and the local object destruction is done by the compiler. When the object is destroyed, it will automatically call the destructor to complete the cleanup of resources in the object.

析构函数是特殊的成员函数,其特征如下:
1. 析构函数名是在类名前加上字符 ~2. 无参数无返回值类型。
3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构
函数不能重载
4. 对象生命周期结束时,C++编译系统系统自动调用析构函数

copy constructor

Copy constructor: There is only a single formal parameter, which is a reference to the object of this class type (usually const decoration), which is automatically called by the compiler when creating a new object with an existing class type object.

The copy constructor is actually an overload of the constructor with only one parameter .

 Date(const Date& d)  //日期类

Mistakes can occur here, such as

 Date(const Date d)  

In passing parameters by address, passing parameters by address has always been tangled. In fact, if you use parameter passing by value, an infinite recursion will appear. If you want to pass parameters by value, you need parameters, and one of the parameters needs to be passed as a parameter. It's just that the nesting dolls keep circulating. Of course, an error will be reported directly in the compiler.
insert image description here
scenes to be used

1、使用已存在对象创建新对象
2、函数参数类型为类类型对象
3、函数返回值类型为类类型对象

assignment overloading

The function name is: the keyword operator followed by the operator symbol that needs to be overloaded

//日期类
 Date& operator=(const Date& d)
 {
    
    
 if(this != &d)
       {
    
    
            _year = d._year;
            _month = d._month;
            _day = d._day;
       }
        
        return *this;
 }
参数类型:const T&,传递引用可以提高传参效率
返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
检测是否自己给自己赋值
返回*this :要复合连续赋值的含义

Operator overloading in a class takes the argument -1 directly. Because non-static member functions in the class will have this pointer.

static member

Class members declared static are called static members of the class, member variables modified with static are called static member variables; member functions modified with static are called static member functions. Static member variables must be initialized outside the class

class memery
{
    
    
public:
	memery()
	{
    
    
		_a = new int[12];
		cout << "this memey" << endl;
		_c++;
	}
	int
	~memery()
	{
    
    
		delete[] _a;
		cout << "~memery()" << endl;
	}
private:
	int* _a ;
	static int _c;
	const static int  _b = 0;
};
int memery::_c = 2;

Static members do not belong to a specific object. Belongs to the entire class, belongs to all objects. And restricted by class permissions. used 类名::or 对象名.accessed directly. Static member functions can be said to be customized for static members.

//计数创建了多少类
class memery
{
    
    
public:
	memery()
	{
    
    
		++_c;
		cout << "this memey" << endl;
		
	}
	~memery(const memery& d)
	{
    
    
	      _c++;
	}
	 static int get_static()
	{
    
    
		 return _c;
	}
	~memery()
	{
    
    
			_c--;
		cout << "~memery()" << endl;
	}
private:
	static int _c;
};
int memery::_c = 0;

Tomomoto

Friends provide a way to break out of encapsulation, and sometimes convenience. But friends increase coupling and break encapsulation.
When using it, high cohesion and low coupling are usually emphasized, so it will be used less.

Friend keyword friendWhen a function is declared as a friend in a class, members of the class can use members of the class.

Inner class: Concept: If a class is defined inside another class, the inner class is called an inner class. The inner class is an independent class, it does not belong to the outer class, let alone access the members of the inner class through the object of the outer class. Outer classes do not have any privileged access to inner classes.
Inner classes can be said to be natural friends of outer classes

注意:内部类就是外部类的友元类,参见友元类的定义,内部类可以通过外部类的对象参数来访问外部类中的所有成员。但是外部类不是内部类的友元。
特性:
1. 内部类可以定义在外部类的public、protected、private都是可以的。
2. 注意内部类可以直接访问外部类中的static成员,不需要外部类的对象/类名。
3. sizeof(外部类)=外部类,和内部类没有任何关系。

Guess you like

Origin blog.csdn.net/github_73587650/article/details/130129926