C++ core programming | Partition reference function overloading classes and objects

C++ core programming

1 Memory partition model

When the c++ program is executed, the memory size direction is divided into 4 areas:

  • Code area: store the binary code of the function body, managed by the operating system (all codes)
  • Global area: store global variables and static variables and constants
  • Stack area: automatically allocated and released by the compiler, storing function parameter values, local variables, etc.
  • Heap area: allocated and released by the programmer, if the programmer does not release it, it will be played back by the operating system at the end of the program

The meaning of the four areas of memory:
the number of different areas stored, endowed with different life cycles, giving us greater flexibility in programming


1.1 Before the program runs

After the program is compiled, an exe executable program is generated, and the unexecuted program is divided into two areas before and after

Code area:
store the machine instructions executed by the cpu.
The code area is shared.
The code area is read-only.

Global area:
Global variables and static variables are stored here. The
global area includes the constant area, character constant area and other constant areas

(the data in this area is released by the operating system after the program ends)

1.2 After the program runs

Stack area:
automatically allocated and released by the compiler, storing function parameter values, local variables, etc.


  • Note: Do not return the address of the local variable, the data created in the stack area will be automatically released by the compiler

Heap area:
allocated and released by the programmer. If the programmer does not release it, the operating system will playback it at the end of the program.
In C++, new is mainly used to open up memory in the heap area

1.3 new operator

In C++, use the new operator
to open server data in the heap area. The data in the heap area is opened manually by the programmer, manually released, and released using the operator delete.

Syntax: new datatype

The data created by new will return a pointer of the type corresponding to the data

2 quotes

Equivalent to pointer action, simpler than pointer

2.1 Basic use of references

Function: alias the variable
Syntax: data type & alias = original name

int main()
{
	int a = 10;
	int& b = a;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;

	b = 50;
	
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;

	system("pause");
	return 0;
}

2.2 Citation Notes

  • reference must be initialized
  • After the reference is initialized, it cannot be changed

2.3 References as function parameters

Function: When passing parameters in a function, the formal parameter can be used to modify the actual parameter by using the reference technology.
Advantages: It can simplify the modification of the actual parameter by the pointer

2.4 Reference as function return value

Role: references can exist as return values ​​of functions

Note: Do not return local variable reference
Usage: function call as lvalue

2.5 The nature of citations

Essence: The essence of reference is implemented in C++ as a pointer constant

	int a = 10;
	//int * const ref =&a;指针常量是指针指向不可改,也说明为什么引用不可更改
	int& ref = a;
	ref = 20;//内部发现ref是引用,自动转换为*ref = 20 ;

2.6 Constant references

Role: constant references are mainly used to modify formal parameters to prevent misuse

In the function parameter list, you can add const to modify the parameter to prevent the parameter from changing the actual parameter

3 function improvement

3.1 Function default parameters

3.2 Function placeholder parameters

3.3 Function overloading

The function name can be the same to improve reusability

3.3.1 Overview of function overloading

//Satisfy the conditions
//1. The same scope (global)
//2. The function name is the same
//3. The function parameter types are different , or the number is different , or the order is different

//The return value of the function cannot be used as a condition for function overloading
void func(int a, double b)
{ } int func(int a, double b) { }



3.3.2 Notes on function overloading

  • references as overload conditions

void func(int &a)
{
}
//int a=10,调用func(a)

int func(const int a)
{
}
//int a=10,调用func(10)

  • Function overloading encounters function default parameters
    void func(int a,int b=5)
    { } int func(int a) { } func(10)//There is ambiguity in calling, so try to avoid function default parameters




4 Classes and Objects

4.1 Packaging

4.1.1 Significance of encapsulation

Design student class:

#include<iostream>
using namespace std;
#include<string>

class stu
{
    
    
	//访问权限
	// 公共权限
public:
	//属性  --->成员属性  成员变量
	//姓名  
	string N_name;
	//学号
	string N_number;

	//行为  --->成员函数  成员方法
	//显示姓名和学号
	void printname()
	{
    
    
		cout << "姓名:" << N_name << "\t" << "学号:" << N_number << endl;
	}

	//赋值
	void setname(string name)
	{
    
    
		N_name = name;
	}
	void setnumber(string number)
	{
    
    
		N_number = number;
	}
};
int main()
{
    
    
	stu s1;
	//赋值方式1:
	//s1.N_name = "王飞鸿";
	//s1.N_number = "20180550";

	//赋值方式2:
	s1.setname("王飞鸿");
	s1.setnumber("20180551");

	s1.printname();

	stu s2;
	s2.setname("王大侠");
	s2.setnumber("12345678");
	s2.printname();
	
	system("pause");
	return 0;
}

access permission

//public     公共权限  类内可以访问,类外也可以访问
//protected  保护权限  类内可以访问,类外不可以访问  儿子可以访问父亲的保护内容
//private    私有权限  类内可以访问,类外不可以访问  儿子不可以访问父亲的私有内容
class Person
{
    
    
public:
	string m_name;
protected:
	string m_car;
private:
	int m_password;
public:
	void func()
	{
    
    
		 m_name = "张三";
		 m_car = "三轮车";
	     m_password = 123456;
	}
};
int main()
{
    
    
	class Person p1;
	p1.m_name = "李四";
	//p1.m_car = "摩托";
	//p1.m_password = 654321;

	system("pause");
	return 0;
}

4.1.2 Difference between struct and class

//The difference between class and struct
//struct default permission is public public
//class default permission is private private

4.1.3 Member attributes are set to private

//1, you can control the read and write permissions by yourself
//2, you can check the validity of the data for writing

class Person
{
    
    
public:
	//设置姓名
	void setName(string name)
	{
    
    
		m_name = name;
	}
	//获取姓名
	string getName()
	{
    
    
		return m_name;
	}

	//获取年龄
	int getAge()
	{
    
    
		//m_age = 0;//初始化为0岁
		return m_age;
	}

	void setAge(int age)  //2、对于写可以检测数据的有效性
	{
    
    
		if (age < 0 || age>150)
		{
    
    
			cout << "你对人的年龄有误解" << endl;
			return;
		}
		m_age = age;
	}

	//设置密码
	void setPassword(string password)
	{
    
    
		m_password = password;
	}

private:
	//姓名 可读可写
	string m_name;

	//年龄 只读
	int m_age;

	//密码 只写
	string m_password;
};
int main()
{
    
    
	Person p;
	p.setName("jhon");
	cout << "姓名:"<< p.getName() << endl;

	//p.m_name = 18;无法直接访问
	//p.getAge(18);只读状态,不能更改
	

	p.setPassword("jhon");//只能写

	p.setAge(180);
    cout << "年龄:"<< p.getAge() << endl;//若p.setAge(int age)中输入<0||>150,输出年龄会乱码

	system("pause");
	return 0;

}

Case: Cube class

class cube
{
    
    
public:
	//行为  //1
	
	void setL(int l)//设置长
	{
    
    
		m_L = l;
	}

	int getL()      //获取长
	{
    
    
		return m_L;
	}

	void setW(int w)//设置宽
	{
    
    
		m_W = w;
	}
	
	int getW()      //获取宽
	{
    
    
		return m_W;
	}

	
	void setH(int h)//设置高
	{
    
    
		m_H = h;
	}
	
	int getH()      //获取高
	{
    
    
		return m_H;
	}
	int caculateS()//获取面积 
	{
    
    
		return 2 * m_L * m_W + 2 * m_W * m_H + 2 * m_L * m_H;
	}

	int caculateV()//获取体积
	{
    
    
		return m_L * m_W * m_H;
	}
	//2.2成员函数判断立方体
	bool isSamebyclass(cube& c)
	{
    
    
		if (m_L == c.getL() && m_W == c.getW() && m_H == c.getH())
		{
    
    
			return true;
		}
		return false;
	}

private:
	//属性
	int m_L;//长
	int m_W;//宽
	int m_H;//高

};


//2.1全局函数判断立方体是否相等 //跳出class
bool isSame(cube& c1, cube& c2)
{
    
    
	if (c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH())
	{
    
    
		return true;
	}
	return false;
}


int main()
{
    
    
	//创建立方体对象c1
	cube c1;
	c1.setL(10);
	c1.setW(10);
	c1.setH(10);
	cout << "该立方体面积:"<<c1.caculateS() << endl;
	cout << "该立方体体积:"<<c1.caculateV() << endl;
	
	//创建第二个立方体对象c2
	cube c2;
	c2.setL(10);
	c2.setW(10);
	c2.setH(10);
	
	//全局函数判断
	bool ret= isSame(c1, c2);
	if (ret)
	{
    
    
		cout << "全局函数:c1和c2是相等的" << endl;
	}
	else
	{
    
    
        cout << "全局函数:c1和c2是不相等的" << endl;
	}
	
	//成员函数判断
	ret = c1.isSamebyclass(c2);
	if (ret)
	{
    
    
		cout << "成员函数:c1和c2是相等的" << endl;
	}
	else
	{
    
    
		cout << "成员函数:c1和c2是不相等的" << endl;
	}

	system("pause");
	return 0;
}

4.2 Object initialization and cleanup

4.2.1 Constructors and Destructors

  • Constructor: The main function is to assign values ​​to the member properties of the object when creating the object. The constructor is automatically called by the compiler and cannot be called manually
  • Destructor: The main function is to automatically call the system before destruction to perform some cleaning work

Constructor syntax: class name () {}
1. Constructor, no return value and no void
2. The function name is the same as the class name
3. The constructor can have parameters, so overloading can occur
4. When the program calls the object The constructor will be called automatically, it cannot be called manually, and it will only be called once

Destructor syntax: ~ class name () {}
1. Destructor, no return value, no void
2. The function name is the same as the class name, add a symbol before the name~
3. The destructor cannot have parameters , so it cannot be overloaded
4. The program will automatically call the destructor before the object is destroyed, no need to call manually, and it will only be called once

4.2.2 Classification and call of constructor

#include<iostream>
using namespace std;


class person
{
    
    
public:
//1.构造函数的分类
	//按参数分类  有参构造 无参构造(默认构造)
	//按类型构造  普通构造 拷贝构造
	
	//构造
	person()
	{
    
    
		cout << "构造函数中无参构造person的调用" << endl;
	}

	person(int a )
	{
    
    
		age = a;
		cout << "构造函数中有参构造person的调用" << endl;
	}

	person(const person &p)
	{
    
    
		age = p.age;
		cout << "构造函数中拷贝构造person的调用" << endl;
	}
	//析构
	~person()
	{
    
    
		cout << "析构函数~person的调用" << endl;
	}

	int age;
};

//2.构造函数的调用
void test01()
{
    
    
	//2.1 括号法
	person p1;
	person p2(5);
	person p3(p2);
	//注意事项1:person p1不能写成person p1(),即不能加括号,因为编译器会误认为是声明
	
	//2.2 显示法
	person p4 = person(5);
	person p5 = person(p4);
	//person(5);//单独写是匿名对象,当前行结束后马上回收,开始析构
	//注意事项2:不要利用拷贝函数匿名初始化对象,编译器会认为person (p3)===person p3(声明) 则发生"重定义"
	//person(p2);
	
	//2.3 隐式转换法
	person p6 =8;  //person p6 =person p(8)
	person p7 = p6;//person p7 =person (p6)

}



int main()
{
    
    
	
	test01(); //控制窗都显示
	//person p;   //区别构造和析构 (析构在该main函数执行完后释放~person())

	system("pause");
	return 0;
}

4.2.3 Copy function call timing

three conditions:

  • Initialize a new object using an already created object
  • Passing by value to function parameters
  • returns the local object by value

4.2.4 Constructor calling rules

By default, the C++ compiler adds at least 3 functions to a class

1. Default constructor (no parameters, function body is empty)
2. Default destructor (no parameters, function body is empty)
3. Default copy constructor, copy the value of the attribute

Constructor calling rules:

  • If the user defines a parameterized structure, C++ no longer provides a default parameterless structure, but will provide a default copy structure
  • If the user defines the copy construction, C++ no longer provides other constructors

4.2.5 Deep Copy and Shallow Copy

  • Shallow copy: simple assignment copy operation
  • Deep copy: re-apply for space in the heap area for copying
拷贝构造函数//new新建内存
person(const person& p)
{
    
    
	cout << "拷贝构造函数:" << endl;
	//如果不利用深拷贝在堆区新建内存,会导致浅拷贝带来的重复释放堆区问题
	m_age = p.m_age;
	m_height = new int(*p.m_height);
}
析构函数//释放new新建的内存
~person()
{
    
    
	cout << "析构函数" << endl;
	if (m_height != NULL)
	{
    
    
		delete m_height;
	}
}

4.2.6 Initialization List

Role: C++ provides initialization list syntax for initializing properties

Syntax: Constructor():Property1(value1),Property2(value2);...{}

class person
{
    
    
public:
	person(int a, int b, int c) :m_A(a), m_B(b), m_C(c){
    
    }

	int m_A;
	int m_B;
	int m_C;
};

void print()
{
    
    
	person p(10, 20, 30);
	cout << "m_A=" << p.m_A << endl;
	cout << "m_B=" << p.m_B << endl;
	cout << "m_C=" << p.m_C << endl;
}
int main()
{
    
    
	print();

	system("pause");
	return 0;
}

4.2.7 Class objects as class members

  • When other objects are members of this class, the class object is constructed first, and then itself is constructed
  • Destruction is in the opposite order of construction
//手机类
class Phone
{
    
    
public:
	Phone(string name)
	{
    
    
		m_Pname = name;
	}
	string m_Pname;
};
//人类
class Person
{
    
    
public:
	Person(string name,string pname):m_Name(name), m_Phone(pname)
	{
    
    
	
	}
	string m_Name;
	Phone m_Phone;
};

void test01()
{
    
    
	Person p("jack", "小米");
	cout << p.m_Name << "有" << p.m_Phone.m_Pname << endl;

}
int main()
{
    
    
	test01();

	system("pause");
	return 0;
}

4.2.8 Static member functions

Static member is to add keyword static before member variable and member function, called static member

Static members are divided into:

  • Static member variables
    1. All objects share the same data
    2. Allocate memory during compilation
    3. In-class declaration, out-of-class initialization

  • Static member functions
    1. All objects share the same function
    2. Static member functions can only access static member variables

Two access methods:
1. Access
person P through the object;
p.func();


2. Access person::func() by class name ;

4.3 Object model and this pointer

4.3.1 Member variables and member functions are stored separately

Only non-static member variables belong to objects of the class

4.3.2 The concept of this pointer

The this pointer points to the object to which the called member function belongs

use:

  • When the formal parameter and the member variable have the same name, the this pointer can be used to distinguish this–>
  • To return the object itself (returning an object rather than a value) in a non-static member function of a class, use return *this

4.3.3 Null pointer access member function

A null pointer can access members, but a null pointer cannot access attributes

Use the following code to avoid program crashes

if(tihis == NULL )
{
    
    
     return}

The essence of the this pointer: the pointing of the pointer constant pointer cannot be modified

4.3.4 const modified member function

Constant function:
void func() const

  • Member functions are called constant functions after adding const
  • Member attributes cannot be modified in constant functions
  • After the keyword mutable is added to the member attribute declaration, it can still be modified in the constant function

Constant object:

  • Add const before declaring an object to call it a constant object
  • Constant objects can only call constant functions

4.4 Tomomoto

Good friends (friend) can access private

4.4.1 Global functions as friends

friend void func(Person * p1);

4.4.2 Classes as friends

friend class GoodGay;

4.4.3 Member functions as friends

friend void GoodGay::visit();

4.5 Operator overloading

4.6 Inheritance

4.6.1 Basic syntax

Purpose: reduce duplication of code
Syntax:
class subclass: inheritance method parent class;
class A: public B;

A is called subclass also called derived class
B is called parent class also called base class

//公共页面(Java、Python、C++...)
class BasePage 
{
    
    
     (公共的内容)
}
 //java页面
 class Java:public BasePage//语法
 {
    
    
 public:
    (写不一样的)
 }

4.6.2 Inheritance method

There are three types:

  • public inheritance
  • protected inheritance
  • private inheritance

4.6.3 Object Models in Inheritance

4.6.4 Construction and destruction order in inheritance

4.6.5 Inheritance of members with the same name

4.6.6 Inheritance of static members with the same name

4.6.7 Multiple inheritance syntax

4.6.8 Diamond Inheritance

4.7 Polymorphism

4.7.1 Basic concepts of polymorphism

Polymorphism is one of the three object-oriented features of C++.
Polymorphism is divided into two categories:

  • Static polymorphism: Function overloading and operator overloading belong to static polymorphism, taking the function name
  • Dynamic polymorphism: derived classes and virtual functions implement runtime
    polymorphism The difference between static polymorphism and dynamic polymorphism:
  • Static polymorphic function address early binding - determine the function address during compilation
  • Late binding of function address of dynamic polymorphism - the function address is determined during the running phase
    Dynamic polymorphism satisfies the conditions:
    1. There is an inheritance relationship
    2. The subclass rewrites the virtual function in the parent class –> add virtual
    rewrite: function return type function name The argument list is exactly the same

4.7.2 Polymorphic Case 1 Calculator

4.7.3 Pure imaginary numbers and abstract classes

4.7.4 Polymorphic Case 2 Making Drinks

4.7.5 Virtual and pure virtual destruction

4.7.6 Polymorphism Case 3 Computer Assembly

5 file operations

To be continued...

Guess you like

Origin blog.csdn.net/qq_46248455/article/details/120649101