C++ Primer (temporarily completed)

C++ Primer

C++ prerequisites

Object-Oriented Programming (OOP)

image-20210802174233194

What is a class and what is an object

Classes contain data and operations

image-20210802174655217

generic programming

Independent of a particular data type,

It has nothing to do with the data type, no matter what data type you are, only realize this function

image-20210802175703932

image-20210802180020700

image-20210802180227120

Chapter 2 begins to learn C++

main function frame

image-20210802181521123

g++ is for compiling c++ tools

image-20210802182645810

The beginning of any program starts from main

image-20210802182751129

The single chip microcomputer can be used without main, and the dynamic link library can also be used without main.

note

//两个斜线,单行注释
/**/ 多行注释

2.1.3 C++ preprocessor and iostream files

#include <iostream>
using namespace std:
想要输入输出,就要有这两个

I included the iostream file, and all the files in the iostream will be included~

image-20210802184626446

input output 流

image-20210802184729038

image-20210802184751350

image-20210802184827973

image-20210802184838787

If you want to call the c library, add c in front and remove the point h

namespace

using compiler directive

image-20210802185020652

If we want to have two wrapped functions

Both, both have wanda() function

Which do we use?

image-20210802185233573

We can find a specific one using this

image-20210802185430883

If you don't add using namespace, you need std:: like this

Then if you add it, it will come from the std namespace by default

image-20210802185653850

That way, we're only using a little bit,

After the declaration, only the std method count endl cin is opened, and these three can be used casually afterwards

Chapter 2 Output and Input

image-20210802205325465

image-20210802205454191

image-20210802205501767

outputstream, to stream the string to the output

image-20210802205525546

The right side information is inserted into the output stream

image-20210802205641117

image-20210802205655669

operator overloading,

These two operators are the same

image-20210802205739295

Multiple symbols, the compiler will recognize

endl control character

end line

end this line

The role is to restart a row

image-20210802205838913

image-20210802205854158

line break

image-20210802210024780

cout << "" << endl

standard writing format

c++ source code style

image-20210802210127478

Program Listing 2.2

#include<iostream>
int main() {
	using namespace std;
	cout << "hello world\n";
	cout << endl;
	return 0;
}

C++ can be defined before the first use

image-20210802210502166

#include<iostream>
int main() {
	using namespace std;

	int carrots;

	carrots = 25;
	cout << carrots << endl;

	int c = 10;
	cout << c << endl;

	return 0;
}

image-20210802210541788

The printed string 25 is stored in the memory as 11001 numbers

cout will output string

#include<iostream>
int main() {
	using namespace std;

	int carrots;

	carrots = 25;
	cout << carrots << endl;

	int c = 10;
	cout << c << endl;

	cout << "i have" << c << "is" << carrots << endl;
	return 0;
}

enter

cin input stream

image-20210803104332973

image-20210803104809396

#include<iostream>

int main() {
	using namespace std;
	int carrots;

	cout << "hello can you guess" << endl;

	cin >> carrots;

	cout << "noooooo " << carrots << endl;

	return 0;
}

image-20210803104959298

A long line can be written like this

class profile

It is equivalent to a data type

image-20210803105342673

Data and methods, right, the same as java

image-20210803105522934

image-20210803105530387

Using methods within objects, you can also use operator overloading

image-20210803105832998

that is<<

pass information to the output stream object

2.4 Functions

function that returns a value

For example the sqrt() function

x = sqrt(6.25)

This is an already written function,

find the square root

image-20210803110610223

image-20210803110744836

The type of parameter passed, the type returned,

must know these two

If the type is missing, it will report an error

image-20210803110939661

It means that he returns double

function declaration, with semicolon

image-20210803111030744

There are two ways to provide a prototype

image-20210803111136206

The second method is better,

The function prototype is in front of main

image-20210803111319410

#include<iostream>
# include<cmath>

int main() {
	using namespace std;
	int carrots;

	cout << "hello can you guess" << endl;

	cin >> carrots;
	
	cout << "noooooo " << carrots << endl;

	double area;
	cout << "Enter the floor area, in square feet,of your home:";
	cin >> area;
	cout << sqrt(area);
	return 0;
}

image-20210803112042924

function variant

image-20210803112252577

function with multiple parameters

pow () how many powers

rand() function without arguments

bucks() function can i have no return value

image-20210803112334660

no return value no parameters

Functions in the standard library~

custom function

image-20210803112810584

image-20210803113241359

#include<iostream>
# include<cmath>

void simon(int n);

int main() {
	using namespace std;

	simon(3);
	return 0;
}

void simon(int n) {
	using namespace std;

	cout << "Simon says touch your toes " << n << " times." << endl;

}

Parameters with return values

image-20210803114215897

#include<iostream>
# include<cmath>

void simon(int n);
int stonetolb(int sts);
int main() {
	using namespace std;

	cout << "Enter the weight in stone:";
	int stone;
	int pounds;
	cin >> stone;
	pounds = stonetolb(stone);
	cout << pounds << endl;
	return 0;
}

void simon(int n) {
	using namespace std;

	cout << "Simon says touch your toes " << n << " times." << endl;

}
//1 stone = 14 lbs
int stonetolb(int sts) {
	int pounds = 14 * sts;
	
	return pounds;
}

programming exercise

image-20210803115910867

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

int hiahia(long x);
int main() {
	cout << "Wum1ng " << "Peking" << endl;
	long x;
	int c;
	cin >> x;
	c = hiahia(x);
	cout << c;

	return 0;
}

int hiahia(long x) {
	return x * 220;
}

image-20210803120036367

image-20210803120055934

image-20210803120224564

image-20210803120318554

Chapter 3 Processing Data

C++ comes natively with built-in data types

primitive data types, | compound data types

Integer Float | String, Array, Structure

simple variable

image-20210803124644605

int braincount;
braincount = 5;

image-20210803124823931

braincount tag name

variable name

alphanumeric underscore

cannot start with a number

no keywords

Two underscores, one underscore, reserved by the compiler,

image-20210803124906589

case sensitive

He stores only a subset of integers

Basic shaping

  • char

  • short

  • int

  • long

  • long long

    image-20210803125623753

image-20210803130104546

just declare

sizeof operator

Find the occupancy in the memory space

image-20210803133300263

To define constants, we generally use all capital letters~

header file limits

contains some macro definitions

image-20210803133416501

image-20210803134059575

image-20210803134339365

image-20210803135047641

initialization

Declaration and assignment merged together

image-20210803135343436

You can also use parentheses for assignment

image-20210803135516688

You can also use {} curly braces initializers

Can be applied to any data type

image-20210803135909882

unsigned type

image-20210803140139487

The maximum value will expand

image-20210803140707377

image-20210803140731260

Let them all +1 and then an out of bounds will occur

image-20210803140959569

integer literal

image-20210803154120095

Decimal, Hexadecimal, Octal

image-20210803154222168

cout defaults to the decimal output of the output

image-20210803154404078

image-20210803154915906

switch cout

image-20210803155013379

Then there are various bases

How C++ determines the type of a constant

suffix can be added

image-20210803155955717

L ul eye

char type, characters and small integers

char is actually an integer, it will be stored as an integer, but it will correspond to a table

One byte is enough 2^8

ASCII

image-20210803161355213

enter a character

image-20210803161624243

cin and cout

image-20210803162720596

It can be seen that it is 77 and M at the same time

image-20210803162743339

If we +1 it becomes 78 which is N

There are variables and functions in the class, we need to access the object, right?

cin, cout can access functions in the class

image-20210803163132622

Let's call the put function of cout to try

escape character

image-20210803163752326

image-20210803163803763

escape sequence using hexadecimal

bool type

image-20210803164951270

The bool type is converted to int, which is 01 conversion

const qualifier

defined as a constant

not allowed to be modified

If the letters are all capitalized, it is generally to use #define

image-20210803165804425

image-20210803165849929

一般使用
const int xx = 111;

so good

We only want a certain constant to be implemented in a certain one, we use const

image-20210803170147462

Use const instead of define

3.3 Floating point numbers

image-20210803170435812

E notation

image-20210803170508942

image-20210803170518145

setf()

Force output to fixed-point representation, preventing conversion to E-notation

image-20210803171425855

Force the display of the last six digits

cout prints the last six digits by default

image-20210803171638163

image-20210803171651532

cout will remove the trailing 0

#include<iostream>
# include<cmath>
#include<climits>
using namespace std;

int main() {

	cout.setf(ios_base::fixed, ios_base::floatfield);
	float tub = 10.0 / 3.0;

	const float million = 1.0E6;
	cout << "tub = " << tub << endl;
	return 0;
}






这里是带乘法的

#include<iostream>
# include<cmath>
#include<climits>
using namespace std;

int main() {

	cout.setf(ios_base::fixed, ios_base::floatfield);
	float tub = 10.0 / 3.0;

	const float million = 1.0E6;
	cout << "tub = " << tub << endl;

	cout << "A million tubs " << million * tub << endl;
	return 0;
}

image-20210803172400478

There has been a problem here

The back is 0

Because the float precision cannot reach

image-20210803172600413

image-20210803172604535

We use double to guarantee precision

#include<iostream>
# include<cmath>
#include<climits>
using namespace std;

int main() {

	cout.setf(ios_base::fixed, ios_base::floatfield);
	float tub = 10.0 / 3.0;

	const float million = 1.0E6;
	cout << "tub = " << tub << endl;

	cout << "A million tubs " << million * tub << endl;


	double mint = 10.0 / 3.0;
	cout << mint * million;
	return 0;
}

Advantages and disadvantages of floating point numbers

When doing operations, floating-point operations will reduce

image-20210803173227786

The difference between a and b is 1.0 but the subtraction is 0, the accuracy is reduced

image-20210803173248798

float double precision

How are floating point numbers stored?

Single precision 32bit

double double precision 64 bit

image-20210804105456645

To follow the IEEE standard, any floating-point number is expressed in scientific notation

binary scientific notation

例如 8.25

整数+小数
1000. 01
0.25 * 2  =0.5 取处整数0
0.5 * 2  = 1 取出整数 1

1000.01转换为科学计数法,
1.00001*2^3
整数部分一定是1

计算机存储科学计数法,有符号的
符号正负(1 bit)
正数 0 负数 1
2^3    2^-3

image-20210804110811723

Because it is necessary to represent positive and negative powers, so

2^(127+3)
计算机中存储浮点数,
一共32位,小数部分23位
精度是6位-7位,说的是十进制,2^23次约等于 10^6.923
符号(1位)+指数位(8位)+小数部分(0001000000000000000)
double类型,小数部分52个

C++ arithmetic operators

Find addition, subtraction, multiplication and division

image-20210804113639420

#include<iostream>
# include<cmath>
#include<climits>
using namespace std;

int main() {
	float hats, head;
	cout.setf(ios_base::fixed, ios_base::floatfield);
	cout << "Enter a number:";
	cin >> hats;
	cout << "enter another number : ";
	cin >> head;
	cout << "heat= " << head <<"\n"<< "hats" << hats << endl;
;
	return 0;
}

image-20210804113819491

Obviously, it is wrong to add

image-20210804113932136

The number of digits will keep increasing

Floating point numbers must be converted to binary, and decimals are always × 2

image-20210804114534690

Comment out this line, that's right

After rounding, it will be correct. Before, it was mandatory to display the last six digits

image-20210804115119192

Addition, subtraction, multiplication and division will have this problem

float type, really not

We're going to use the double type

image-20210804115338483

integer division

image-20210804115437796

Upcast data type

The number of digits is lengthened, and it is converted to double type division by default

image-20210804115542438

If it is forced to float, add an F

image-20210804115607935

image-20210804115714773

image-20210804115742052

Composite type

4.1 Arrays

Arrays store the same data type

image-20210804140529647

The contents of the array are arranged consecutively in memory

image-20210804140653887

These three points must have

short months[12]

声明通用通用格式
typeName arrayName[arraysize]


What must be stored in it is a constant

image-20210804140849038

The numbers in the array start from 0~

The programmer must confirm that the array subscript does not cross the boundary

image-20210804141757702

#include<iostream>
# include<cmath>
#include<climits>
using namespace std;

int main() {
	int yams[3] = {7,8,6};
	int yamscosts[3] = { 20,30,5 };
	cout << "The total yams = " << yams[0] + yams[1] + yams[2] << endl;
	cout << "The package with" << yams[1] << "yams cost " << yamscosts[1] << endl;
	return 0;
}

Array initialization rules

image-20210804142206329

The value can only be given when it is defined

A small part is initialized, others are 0

Can also be empty, the compiler will automatically calculate the number

short things[] = {1,5,3,8}

variable type narrowing

In fact, to put it bluntly, overflow occurs when one variable is assigned to another variable. In case of narrowing conversion, the program will generally not report an error, which will be very harmful to bug debugging, so it should be avoided as much as possible. Without further ado, let's look at an example.

#include <iostream>
using namespace std;

int main()
{
	int a = 5000000; //-2147483648~2147483647
	short int b = a;
	cout << b << endl;
	return 0;
}

image-20210804142721368

It can be clearly seen that the result is not what we want, not even overflow. So how to avoid variable type narrowing conversion? C++11This problem can be avoided by providing an initialization list.

image-20210804142729342

#include <iostream>
using namespace std;

int main()
{
	int a = 5000000, b = 10000; //-2147483648~2147483647
	short int c{a};
	short int d{b};
	cout << c << endl;
	cout << d << endl;
	return 0;
}

image-20210804142839535

The default is 0

image-20210804142922995

Significant bit reduction is not allowed!

that is narrowed

Double is not allowed in long

image-20210804143136313

Array alternative to vector

string

image-20210804143211925

One is, C language style, store the string in the array

The second method based on the string class library

string to \0end with

The first one is not a string

The first is a character array

image-20210804143546071

He will automatically add \0 compiler added

image-20210804143741109

image-20210804143753339

Single quotes are characters, double quotes are strings

There are two double quotes, plus a \0

String constants store addresses

Manipulate strings in an array

strlen string length

sizeof() occupies memory space

image-20210804145844303

15 bytes

strlen string length ignores \0

image-20210804150224979

The second input is gone

we added a space

image-20210804150247234

cin uses whitespace characters (space, carriage return, tab)

determine the string

he thinks the present is over

dreeb will be stored in the buffer

image-20210804150709737

image-20210804152343652

will be placed in the input buffer

Go directly to the buffer to read,

getline()

Read a line of string input each time

cin.getline()

image-20210804152725481

Setting 20 will read up to 19 characters

#include<iostream>
# include<cmath>
#include<climits>
# include<cstring>
using namespace std;

int main() {
	const int Size = 20;
	char name[Size];
	char dessert[Size];
	cout << "11" << endl;
	cin.getline(name, Size);
	cout << "22" << endl;

	cin.getline(dessert, Size);
	cout << "delicious" << dessert << endl;

	return 0;
}

image-20210804155937168

get()

Like getline, it is all about receiving lines

image-20210804155919157

get will discard the newline character and end when it encounters a newline character

image-20210804160028244

It will jump twice directly after entering

image-20210804160052813

empty character, no input

image-20210804160438747

image-20210804160555443

Accept a carriage return in the middle

image-20210804160747326

function overloading

Different parameter lists with the same parameter name

image-20210804161039509

image-20210804161435794

Introduction to the string class

The string can be manipulated by the type of the array, subscript and the like can be

image-20210804162542887

image-20210804162646276

Assignment, splicing, appending

You can assign a string object to another string object

image-20210804162740650

image-20210804162905227

attach

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

int main() {
   char charr1[20];
   char charr2[20] = "jaguar";
   string str1;
   string str2 = "panther";
   cout << "Enter a kind of feline"<< endl;
   cin >> charr1;
   cout << "Enter another kind of feline : ";
   cin >> str1;
   cout << "Here are some felines:\n";
   cout << charr1 << " " << charr2 << " "<< str1 << " " << str2 << endl;

   return 0;
}

image-20210804163221497

strcp(charr1,charr2)

copy

sstr1+=""

strcat(car,“juice”);

z string concatenation

string class I/O

image-20210804163449038

How to use getline to read a large string, stored in string

image-20210804163713045

Check strlen and find that it is different from 20,

Because we did not enter the value, random in memory

We look at str.size()

image-20210804164141979

image-20210804164251270

cin.getline

and

getline

image-20210804164423798

image-20210804165232308

Structure settings

image-20210804165303470

Allow declaration of structure to omit struct

image-20210804165413800

Commas are required when padding

image-20210804165433175

image-20210804165529216

external declaration, visible in all

perk is visible inside the main function

image-20210804165602083

The same structure type can be directly assigned

Structure and Type Direct Declaration

image-20210804194741576

You can also assign

image-20210804194751752

not recommended

image-20210804195302894

image-20210804195327083

bit fields of a structure

image-20210804195410613

Marks how many bits you have, how many bits

Bit fields are low-level programming

image-20210804195538501

4.5 Union

union is a data format

image-20210804200949954

image-20210804200715035

In the union, choose one of the three, and only one can be used at the same time

image-20210804200805061

image-20210804200929014

very similar to struct

image-20210804201021440

The union length is the maximum length

image-20210804201536849

#include<iostream>
using namespace std;

union one2all {
	char ch;
	int n;

};

int main() {
	one2all num;
	cout << "sizeof(num)= " << sizeof(num) << endl;
	return 0;
}

image-20210804201731934

For example, if you save an A, it will output 65 as an int, and output A as a string.

the same memory space

The structure can be placed in the structure, and the structure can be placed in the union

image-20210804202012659

You can use the union to check whether the computer is in big-endian mode or little-endian mode

4.6 Enumeration

C++'s enum tool provides a way to create symbolic constants

It is also equivalent to struct

image-20210804202110393

image-20210804202214111

In this case, red, orange, etc., all become constants

Each value inside is an integer, starting from zero

image-20210804202501680

Enumeration types declare such variables,

spectrum band

At the same time, only the enumeration that defines the enumeration can be assigned to the variable of the enumeration

Can only give 0-7 or red, etc.

Enumeration type, only assignment, no arithmetic operations

image-20210804202815571

image-20210804202840530

Can be converted to int such as 0 1 and the like

low to high

image-20210804202915068

Enumerated types, in order to define constants, not create new constants

set enumeration value

image-20210804203107413

Like knowing integers

image-20210804203257276

He has an upper limit and a lower limit, just assign a value here

His limit must be the largest power of 2 (three times of 2 = 8 four times of two - 1 is 15)

image-20210804203357383

4.7 Pointers and free memory

image-20210805101527656

Where is it stored?

What is the value,

What type of information is stored

Ask for his worth address,

image-20210805103558314

Add an address symbol

How to declare a pointer

Put the address in the pointer

image-20210805104854316

#include<iostream>
using namespace std;



int main() {
	int updates = 6;
	int *p_updates;
	p_updates = &updates;
	cout << "value : updates = " << updates << endl;
	cout << "p_updates = " << p_updates << endl;
	return 0;
}

image-20210805105057918

4.7.2 Dangers of pointers

image-20210805105152710

His address is not clear, there will be bugs in sending values ​​to the address

image-20210805105651092

4.7.4 Using new to allocate memory

A pointer is an alias for accessing memory

The new operator allocates memory, which is much better than malloc

new will return the address of the memory block

image-20210805110515276

int *pn = new int;

typeName * pointer_name = new typeName

image-20210805111330726

#include<iostream>
using namespace std;



int main() {
	int nights = 1001;
	int *pt = new int;
	*pt = 1001;

	cout << "nights value = " << nights << "address " << &nights << endl;
	cout << "int value = " << *pt << "address value = " << pt << endl;
	double * pd = new double;
	*pd = 10000001.0;
	cout << "double value = " << *pd << "address " << pd << endl;
	return 0;
}

image-20210805111344221

Use delete to release memory

Only the memory space will be deleted and released, and the ps pointer will not be deleted.

new and delete should be used in pairs,

Do not delete after delete, the result is unpredictable

delete does not release the memory acquired by the declared variable

image-20210805111627816

image-20210805111712083

Without new, you cannot delete

For small data, just define it directly, for a large amount of data, it is still convenient to use new

image-20210805114250749

Creating an array statically is wasteful. When new, you don’t need to create space if you don’t need it

dynamic binding

Use new to create dynamic arrays

image-20210805114404140

int * psome = new int [10];

Free the array:

delete [] psome;

without square brackets

Only the first element is released

image-20210805114639010

image-20210805114756661

Pointers are variables, array values ​​are constants

Arrays cannot be added/operated, etc.

pointers, arrays, pointer arithmetic

image-20210805143708644

image-20210805144350913

Dynamic and static binding of arrays

image-20210805144509867

use new[]

image-20210805144520202

No allocation

pointers and strings

image-20210805144716313

It is equivalent to printing the first letter r of rose, taking out all the strings at once, rose until it finds \0

strncpy () how many copies

image-20210805145257571

prevent overflow

image-20210805145354644

new char array

Dynamically open up space

new dynamically creates a structure

better than compile time

image-20210805145527150

structure type pointer

image-20210805160905284

image-20210805160931927

image-20210805160957458

This can also be achieved

Receive dynamic string to open up space function

image-20210805161446124

image-20210805161700926

image-20210805161740836

type combination

Array Alternatives

image-20210805161910066

template class vector

image-20210805162241199

Parentheses are used here

vector<typeName> vt(n_elem);

vector cost, the efficiency is relatively low

Powerful

template class array

The array length is a fixed array

array<int ,5> ai;

image-20210805162736275

image-20210805163704130v

vector is stored in the heap, it must be different from other storage]

#include<iostream>
#include<vector>
#include<array>
using namespace std;



int main() {
	int nights = 1001;
	double a1[4] = { 1.2,2.4,3.6,4.8 };
	vector<double> a2(4);
	a2[0] = 1.0 / 3.0;
	a2[1] = 1.0 / 5.0;
	a2[2] = 1.0 / 7.0;
	a2[3] = 1.0 / 9.0;
	array<double, 4> a3 = { 3.14,2.72,1.62,1.41 };
	array<double, 4> a4;


	return 0;
}

Using member functions, you can use at to detect subscript out of bounds

image-20210805164328280

cycle

image-20210805165241875

In this way without parentheses, he will separate the two sides with an equal sign

do not know

image-20210805165826623

output like 0 1

image-20210805170900188

output of factorial

Chapter 8 Exploring Functions

C++ intrinsics

In order to improve the program running speed

image-20210805180150808

run fast

image-20210805180800578

Regular functions, waste of time

Expend energy, push in and out of the stack

If the code execution is short, it is convenient to inline

image-20210805201143377

image-20210805201239051

square is an inline function

#include<iostream>

using namespace std;

inline double square(double x) { return x * x; };

int main() {
	double a, b;
	double c = 13.0;

	a = square(5.0);
	b = square(4.5 + 7.5);
	cout << "a = " << a << "b = " << endl;
	cout << "c = " << c << endl;
	cout << "Now c = " << square(c++) << endl;
	
	return 0;
}

8.2 Reference variables

A reference is an alias that defines a variable

image-20210805201817437

Create reference variable

image-20210805201853474

rats and rodents are interchangeable

There is a difference between references and pointers

image-20210805202630895

Use references as function arguments

It's a matter of formal parameters and actual parameters.

Formal parameters manipulate arguments,

out of C language

image-20210805203814240

The name is the same, but the parameters are different, it is also ok~

8.5 Function Templates

swaps the values ​​of two numbers

How to write it?

image-20210806101646997

Function overloading, you can also use function templates

The c++ function template feature can automate this process

image-20210806101833597

template <typename anytype>

almost the same as class

image-20210806101922692

Optional type name

For convenience, T is generally written to save trouble

Any type can be accepted~

image-20210806102705808

Two replacements, either template function or function overloading

image-20210806103308652

#include<iostream>

using namespace std;

template<typename T>
void Swap(T &a, T &b);

int main() {
	int i = 10;
	int j = 20;
	cout << "i,j = " << i << "," << j << "." << endl;
	Swap(i, j);
	cout << "after swap ,now i,j = " << i << "," << j << endl;

	double x = 24.5;
	double y = 81.7;
	cout << "i,j = " << x << "," << y << "." << endl;
	Swap(x, y);
	cout << "after swap ,now i,j = " << x << "," << y<< endl;
	return 0;
}

template <typename T>
void Swap(T &a,T &b) {
	T temp;
	temp = a;
	a = b;
	b = temp;
}

Writing is one, but the compiler will eventually compile and generate two

8.5.1 Overloaded Templates

If we want to exchange arrays, we must overload, and it is obviously impossible without overloading

image-20210806105114652

There is nothing wrong with the output

#include<iostream>

using namespace std;

template<typename T>
void Swap(T &a, T &b);
const int LIM = 8;
void show(int arr[], int n);

int main() {
	int i = 10;
	int j = 20;
	cout << "i,j = " << i << "," << j << "." << endl;
	Swap(i, j);
	cout << "after swap ,now i,j = " << i << "," << j << endl;

	int d1[LIM] = { 0,7,0,4,1,7,7,6 };
	int d2[LIM] = { 0,7,2,0,1,9,6,9 };
	cout << "origianl arrays" << endl;
	show(d1, LIM);
	show(d2, LIM);

	return 0;
}

template <typename T>
void Swap(T &a,T &b) {
	T temp;
	temp = a;
	a = b;
	b = temp;
}
void show(int arr[], int n) {
	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";

	}
	cout << endl;

}

Let's write the template

image-20210806105945291

#include<iostream>

using namespace std;

template<typename T>
void Swap(T &a, T &b);
template<typename T>
void Swap(T a[], T b[], int n);
const int LIM = 8;
void show(int arr[], int n);

int main() {

	int d1[LIM] = { 0,7,0,4,1,7,7,6 };
	int d2[LIM] = { 0,7,2,0,1,9,6,9 };
	cout << "origianl arrays" << endl;
	show(d1, LIM);
	show(d2, LIM);
	Swap(d1, d2, LIM);
	cout << "Swapped arrays = " << endl;
	show(d1,LIM);
	show(d2, LIM);

	return 0;
}

template <typename T>
void Swap(T &a,T &b) {
	T temp;
	temp = a;
	a = b;
	b = temp;
}
template<typename T>
void Swap(T a[], T b[], int n) {
	T temp;
	for (int i = 0; i < n; i++) {
		temp = a[i];
		a[i] = b[i];
		b[i] = temp;
	}
}
void show(int arr[], int n) {
	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";
	}
	cout << endl;

}

8.5.2 Limitations of templates

image-20210806110203065

image-20210806110739729

Exchange structure, directly exchange everything

image-20210806110802109

I just want to exchange money,

image-20210806110826089

Overloading, parameter type, number need to be different

8.5.3 Explicit reification

template <> void Swap(job &j1,job &j2)

image-20210806111705501

tell the compiler. If the job type is passed in, you cannot use other templates

image-20210806113336500

successfully replaced

#include<iostream>

using namespace std;

template<typename T>
void Swap(T &a, T &b);
template<typename T>
void Swap(T a[], T b[], int n);
const int LIM = 8;
void show(int arr[], int n);


struct job
{
	char name[40];
	double salary;
	int floor;
};

template <> void Swap<job>(job &j1, job &j2);
void show(job &j);

int main() {

	int d1[LIM] = { 0,7,0,4,1,7,7,6 };
	int d2[LIM] = { 0,7,2,0,1,9,6,9 };
	cout << "origianl arrays" << endl;
	show(d1, LIM);
	show(d2, LIM);
	Swap(d1, d2, LIM);
	cout << "Swapped arrays = " << endl;
	show(d1,LIM);
	show(d2, LIM);

	job Rick = { "Rick",100,10 };
	job Jack = { "Jack",1100,11 };
	show(Rick);
	show(Jack);
	Swap(Rick, Jack);
	show(Rick);
	show(Jack);

	return 0;
}

template <typename T>
void Swap(T &a,T &b) {
	T temp;
	temp = a;
	a = b;
	b = temp;
}
template<typename T>
void Swap(T a[], T b[], int n) {
	T temp;
	for (int i = 0; i < n; i++) {
		temp = a[i];
		a[i] = b[i];
		b[i] = temp;
	}
}
void show(int arr[], int n) {
	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";
	}
	cout << endl;

}
void show(job &j) {
	cout << j.name << ":" << j.salary << "onfloor" << j.floor << endl;
}
template <> void Swap<job>(job &j1, job &j2) {
	double t1;
	int t2;

	t1 = j1.salary;
	j1.salary = j2.salary;
	j2.salary = t1;

	t2 = j1.floor;
	j1.floor = j2.floor;
	j2.floor = t2;
}

Show reified functions first

8.5.4 Instantiation and Reification

image-20210806120010031

Choose the appropriate function call yourself

image-20210806120210655

We define a template function and a non-template function

image-20210806174943976

Non-template functions take precedence

image-20210806175052811

#include<iostream>

using namespace std;
template<class T>
T lesser(T a, T b) {
	return a < b ? a : b;
}

int lesser(int a, int b) {
	a = a < 0 ? -a : a;
	b = b < 0 ? -b : b;
	return a < b ? a : b;
}
int main(void) {
	int m = 20;
	int n = -30;

	double x = 15.5;
	double y = 25.9;
	cout << lesser(m, n) << endl;
	return 0;
}

image-20210806175305318

In this way, template functions are preferred

image-20210806175338853

#include<iostream>

using namespace std;
template<class T>
T lesser(T a, T b) {
	return a < b ? a : b;
}

int lesser(int a, int b) {
	a = a < 0 ? -a : a;
	b = b < 0 ? -b : b;
	return a < b ? a : b;
}
int main(void) {
	int m = 20;
	int n = -30;

	double x = 15.5;
	double y = 25.9;
	cout << lesser(m, n) << endl;

	cout << lesser<>(m, n) << endl;
	return 0;
}

image-20210806175557349

Tell the template function that the parameter is forced to int

image-20210806175619043

compile separately

A project may contain many source code and header files

Except for inline functions, other definitions do not put header files

image-20210806183835926

You can write .c .cpp specifically to call other

Put those things in the header file

One function, one cpp is more fragrant

image-20210806190720342

Take the two apart, compile, and link

image-20210806191257251

It is guaranteed that the project will only be defined once,

if not define If it has not been defined, then the header file will be defined,

There is an if must have an endif

image-20210806194025143

Double quotes, means to go to your current directory to get the header file

function call

file1.cpp

# include<iostream>
#include "coordin.h"
using namespace std;
int main(void) {
	rect rplace;
	polar pplace;

	cout << "Enter the x and y values :";
	while (cin >> rplace.x >> rplace.y) {
		pplace = rect_to_polar(rplace);
		show_polar(pplace);
		cout << "Next two number (q to quit):";

	}
	return 0;
}

function prototype declaration.h

#pragma once
#pragma once
#ifndef __COORDIN_H__
#define __COORDIN_H__

struct polar
{
	double distance;
	double angle;
};

struct rect {
	double x;
	double y;
};

polar rect_to_polar(rect xypos);
void show_polar(polar dapos);


#endif // !__COORDIN_H__

function definition

file2.cpp

#include<iostream>
#include<cmath>
#include "coordin.h"

using namespace std;

polar rect_to_polar(rect xypos) {
	polar answer;

	answer.distance = sqrt(xypos.x * xypos.x + xypos.y * xypos.y);
	answer.angle = atan2(xypos.y, xypos.x);

	return answer;
}
void show_polar(polar dapos) {
	const double Rad_to_deg = 57.29577951;

	cout << "distance = " << dapos.distance << endl;
	cout << "angle = " << dapos.angle * Rad_to_deg << " degree " << endl;

}

Storage order, scope and linkage

image-20210809181220011

Formal parameters, actual parameters, and the area of ​​​​parameters, c has learned

Using auto in C++11

register auto

image-20210809193143340

extern

image-20210809193211834

Declare the function, indicating that this parameter is foreign, just want to use it here

Scope Resolution Operators

image-20210809193615620

::

After adding, it is equivalent to calling a global variable

image-20210809193637034

The ::warming here indicates the global version used

support.cpp

#include "support.h"

using namespace std;

void update(double dt) {
	warming += dt;
	cout << "Update" << warming << endl;


}
void local(void) {

}

external.cpp

# include<iostream>
# include "support.h"

using namespace std;

double warming = 0.3;

int main(void) {
	cout << "Global warming is " << warming << "degrees." << endl;
	update(0.1);
	cout << "Global warming is " << warming << "degrees." << endl;
	return 0;
}

support.h

#pragma once
#ifndef __SUPPORT_H__
#define __SUPPORT_H__

#include<iostream>
extern double warming;
void update(double dt);
void local(void);

#endif


static persistence, internal linkability

image-20210809193947223

image-20210809194030930

Internal only for internal files,

image-20210809194145005

Proximity principle, almost~

file1.cpp

image-20210809194659434

file2.cpp

image-20210809194706990

unlinked local variables

Other functions, files, can't see you

image-20210809195225124

cin.get() Get content

image-20210809195755426

image-20210809195742972

image-20210809195909636total is only called for the first time. count will drop the initialization bit 0 once

image-20210809200102444

The total value will not change after

specifiers and qualifiers

auto automatically matches the variable type

register allocates memory to a register

image-20210809200333388

image-20210809200500361

CV qualifier

volatile和mutable

Firmware uses more

const

Linkability is internal and does not affect other files

Functionality and Linkability

C++ does not allow a function to define another function, and all function storage persistence is static

The extern function indicates that it is defined in another file, it is optional, and it is not written by default

Function static definition, can only be used in one file

image-20210809200731989

language linkage

C language one name one function

image-20210809200808322

There may be multiple functions with the same name in C++

image-20210809200835572

Compiler may change his name

Storage schemes and dynamic allocation

new opens up, delete releases

Initialize with new

image-20210809200955109

image-20210809201025877

Open up memory space, the initial value is 6

image-20210809201050598

image-20210809201122997

image-20210809201142137

positioning new operator

image-20210809201306464

You can specify where to store

use new

Handles the hardware accessed at a particular location i or creates an object

image-20210809201310440

image-20210809201353737

image-20210809201424626

specified in that memory space,

specified in buffer1

new positioning operator, requires new header file

image-20210809201834475

image-20210809201851729

image-20210809202156524

C++, we want to output the address of the string, buffer, such a positive string, we need to force conversion, let him know our address

image-20210809202230568

image-20210809202343187

Obviously, the two addresses are different

image-20210809202513056

image-20210809202914339

We found that pd2 is the same as buffer

when delete

image-20210809203018870

delete cannot be used with the positioned new operator

delete deletes dynamic memory, dynamically releases memory, and new also

image-20210809203513883

9.3 Namespaces

Libraries from different manufacturers may conflict~

image-20210809203628499

9.3.2 New namespace features

image-20210809203736400

We can use any name, when we use it, just write it specifically

Namespaces can also contain namespaces, which are external by default, but not in code blocks

image-20210809203830192

new name, just add

image-20210809203844444

image-20210809203908771

Of course, the scope resolution operator is required

named

using declaration and using pragma

image-20210809204011161

image-20210809204030477

image-20210809204112150

into the local declaration area

compiler directive

image-20210809204151941

image-20210809204219246

image-20210809204253850

image-20210809204815632

If you use fetch, local variables will be prioritized and there will be no conflicts

image-20210809205314291

Application of namespace

image-20210809205328035

Such using compilation instructions

image-20210809205338587

unnamed namespace

image-20210809205446494

Start with statement, end with

Chapter 10 Classes and Objects

Call private private data through public methods

The header file only declares the class, and does not write it out

Access control

image-20210810105140190

Only through public can change private

Control access to members, public or private

Without private, the data is private by default.

image-20210810105838144

stock00.h header file

#pragma once
#ifndef __STOCK00__H__
#define __ STOCK00__H__
#include<string>

class Stock
{
private:
	std::string company;
	long shares;
	double share_val;
	double total_val;
	void set_total() { total_val = shares * share_val };
public:
	void acquire(const std::string &co,long n,double pr);//哪一个公司的股票
	void buy(long num, double price);
	void sell(long num, double price);
	void update(double price);
	void show();

};


#endif

10.2.3 Implementing class member functions

image-20210810110123221

Use :: to identify the class

image-20210810110201735

image-20210810110210139

We can define the same function with another

Within the class, no need to specify

inline method

image-20210810111949374

Functions defined in the class declaration will automatically become inline functions

image-20210810112229622

When the function is declared, it is defined, and this automatically becomes an inline function

If there is inline, it will also be an inline function

image-20210810112509807

put it outside

class definition

stock00.cpp

#include<iostream>
#include "stock00.h"



void Stock::acquire(const std::string &co,long n,double pr) {
	company = co;
	if (n < 0) {
		std::cout << "Number of share can't be negative;" << company << std::endl;

	}
	else
		shares = n;

	set_total();
}

void Stock::buy(long num, double price) {
	if (num < 0) {
		std::cout << "number of shares can't be negative,Transaction is aborted" << std::endl;

	}
	else {
		shares += num;
		share_val = price;
		set_total();
	}
}
void Stock::sell(long num, double price) {
	using std::cout;
	if (num) {
		std::cout << "number of shares can't be negative " << std::endl;

	}
	else if (num > shares) {
		cout << "you can't sell more than you have " << std::endl;

	}
	else {
		shares -= num;
		share_val = price;
		set_total();
	}
}

void Stock::update(double price) {
	share_val = price;
	set_total();
}

void Stock::show() {
	std::cout << "Company: " << company << std::endl;
	std::cout << "Shares: " << shares << std::endl;
	std::cout << "share price : " << share_val << std::endl;
	std::cout << "TOtal worth:" << total_val << std::endl;
}

10.2.4 Using classes

#include<iostream>
#include"stock00.h"


int main(void) {
	Stock fluffy_the_cat;
	fluffy_the_cat.acquire("wuwu",20,12.5);//第一次获取一个股票
	fluffy_the_cat.show();
	
	fluffy_the_cat.buy(15, 18.125);//再买多少zhi,meizhi多少钱
	fluffy_the_cat.show();
	
	fluffy_the_cat.sell(400, 20.00);//尝试卖400份,查看报错
	fluffy_the_cat.show();
	
	return 0;
}

image-20210810113410568

image-20210810114101864

image-20210810114645337

Sell ​​too much, prompt, can't sell

class constructor and destructor

image-20210810115201768

image-20210810115617708

parameter cannot be used as a parameter to a constructor

To avoid confusion, we prefix the data with m_

The constructor has no return value~~

stock10.cpp

#include<iostream>
#include"stock00.h"

Stock::Stock(const std::string &co, long n, double pr) {
	company = co;
	if (n < 0) {
		std::cout << "Number of share can't be negative;" << company << std::endl;
		shares = 0;
	}
	else
		shares = n;
	share_val = pr;
	set_total();
}

C++ provides two ways to construct functions, the first is to explicitly call the constructor

use constructor

image-20210810150942461

image-20210810152250202

If you use default parameters, fill in the value directly in the declaration here (default value)

image-20210810152436583

Another way is function overloading to define another constructor, a constructor with no parameters,

Only one of the above two can be used. Otherwise it will conflict

image-20210810152945557

usestock2.cpp

#include<iostream>
#include "stock00.h"
int main(void) {
	/*
	Stock stock1("Nanosmart", 12, 20.0);
	stock1.show();

	Stock stock2 = Stock("Boffo objects", 2, 2.0);
	stock2.show();
	*/
	Stock stock1;
	stock1.show();
}

stock.cpp

#include<iostream>
#include"stock00.h"
/*
Stock::Stock(const std::string &co, long n, double pr) {
	company = co;
	if (n < 0) {
		std::cout << "Number of share can't be negative;" << company << std::endl;
		shares = 0;
	}
	else
		shares = n;
	share_val = pr;
	set_total();
}*/

Stock::Stock() {
	company = "no name";
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}

stock00.h

#pragma once
#ifndef __STOCK00__H__
#define __ STOCK00__H__
#include<string>

class Stock
{
private:
	std::string company;
	long shares;
	double share_val;
	double total_val;
	void set_total() { total_val = shares * share_val; };
public:
	Stock();
	//Stock(const std::string &co, long n, double pr);
	void acquire(const std::string &co,long n,double pr);//哪一个公司的股票
	void buy(long num, double price);
	void sell(long num, double price);
	void update(double price);
	void show();

};


#endif

stock00.cpp

#include<iostream>
#include "stock00.h"



void Stock::acquire(const std::string &co,long n,double pr) {
	company = co;
	if (n < 0) {
		std::cout << "Number of share can't be negative;" << company << std::endl;
		shares = 0;
	}
	else
		shares = n;
	share_val = pr;
	set_total();
}

void Stock::buy(long num, double price) {
	if (num < 0) {
		std::cout << "number of shares can't be negative,Transaction is aborted" << std::endl;

	}
	else {
		shares += num;
		share_val = price;
		set_total();
	}
}
void Stock::sell(long num, double price) {
	using std::cout;
	if (num) {
		std::cout << "number of shares can't be negative " << std::endl;

	}
	else if (num > shares) {
		cout << "you can't sell more than you have " << std::endl;

	}
	else {
		shares -= num;
		share_val = price;
		set_total();
	}
}

void Stock::update(double price) {
	share_val = price;
	set_total();
}

void Stock::show() {
	std::cout << "Company: " << company << std::endl;
	std::cout << "Shares: " << shares << std::endl;
	std::cout << "share price : " << share_val << std::endl;
	std::cout << "TOtal worth:" << total_val << std::endl;
}

image-20210810153048225

If the parameter is passed, it must not be the default constructor

image-20210810153152309

The third, the default constructor

10.3.4 Destructors

image-20210810154313230

After the object is used, the destructor will be called automatically.

If new is used to allocate memory in the constructor, the destructor will call delete to free it

The destructor also has no return value and type

image-20210810154445579

Destructor has no parameters

~Stock();

At the same time, because the last one has no new, the destructor is empty

image-20210810154536807

image-20210810154624248

10.4 The this pointer

image-20210810160024522

If we need to compare two classes,

We want to compare two class objects,

Points to the object used to call the member function, this represents the object being accessed,

image-20210810163247598

tips

image-20210810163258908

*this represents the entire calling object

image-20210810163423399

The return here is*this

The this pointer points to the object of the calling member

10.5 Arrays of Objects

image-20210810171056578

The constructor initializes the array

Guess you like

Origin blog.csdn.net/hxhxhxhxx/article/details/119334165