C++ Primer
- C++ prerequisites
-
- generic programming
- Chapter 2 begins to learn C++
- 2.1.3 C++ preprocessor and iostream files
- namespace
- Chapter 2 Output and Input
- enter
- class profile
- 2.4 Functions
- function variant
- custom function
- programming exercise
- Chapter 3 Processing Data
- sizeof operator
- integer literal
- How C++ determines the type of a constant
- bool type
- 3.3 Floating point numbers
- C++ arithmetic operators
- Composite type
- 4.1 Arrays
- string
- Introduction to the string class
- 4.5 Union
- 4.6 Enumeration
- 4.7 Pointers and free memory
- pointers, arrays, pointer arithmetic
- type combination
- Array Alternatives
- cycle
- Chapter 8 Exploring Functions
- 8.2 Reference variables
- compile separately
- Storage order, scope and linkage
- Using auto in C++11
- static persistence, internal linkability
- specifiers and qualifiers
- Functionality and Linkability
- language linkage
- Storage schemes and dynamic allocation
- 9.3 Namespaces
- Chapter 10 Classes and Objects
- 10.2.3 Implementing class member functions
- 10.2.4 Using classes
- class constructor and destructor
- 10.3.4 Destructors
- 10.4 The this pointer
- 10.5 Arrays of Objects
C++ prerequisites
Object-Oriented Programming (OOP)
What is a class and what is an object
Classes contain data and operations
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
Chapter 2 begins to learn C++
main function frame
g++ is for compiling c++ tools
The beginning of any program starts from main
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~
input output 流
If you want to call the c library, add c in front and remove the point h
namespace
using compiler directive
If we want to have two wrapped functions
Both, both have wanda() function
Which do we use?
We can find a specific one using this
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
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
outputstream, to stream the string to the output
The right side information is inserted into the output stream
operator overloading,
These two operators are the same
Multiple symbols, the compiler will recognize
endl control character
end line
end this line
The role is to restart a row
line break
cout << "" << endl
standard writing format
c++ source code style
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
#include<iostream>
int main() {
using namespace std;
int carrots;
carrots = 25;
cout << carrots << endl;
int c = 10;
cout << c << endl;
return 0;
}
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
#include<iostream>
int main() {
using namespace std;
int carrots;
cout << "hello can you guess" << endl;
cin >> carrots;
cout << "noooooo " << carrots << endl;
return 0;
}
A long line can be written like this
class profile
It is equivalent to a data type
Data and methods, right, the same as java
Using methods within objects, you can also use operator overloading
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
The type of parameter passed, the type returned,
must know these two
If the type is missing, it will report an error
It means that he returns double
function declaration, with semicolon
There are two ways to provide a prototype
The second method is better,
The function prototype is in front of main
#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;
}
function variant
function with multiple parameters
pow () how many powers
rand() function without arguments
bucks() function can i have no return value
no return value no parameters
Functions in the standard library~
custom function
#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
#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
#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;
}
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
int braincount;
braincount = 5;
braincount tag name
variable name
alphanumeric underscore
cannot start with a number
no keywords
Two underscores, one underscore, reserved by the compiler,
case sensitive
He stores only a subset of integers
Basic shaping
-
char
-
short
-
int
-
long
-
long long
just declare
sizeof operator
Find the occupancy in the memory space
To define constants, we generally use all capital letters~
header file limits
contains some macro definitions
initialization
Declaration and assignment merged together
You can also use parentheses for assignment
You can also use {} curly braces initializers
Can be applied to any data type
unsigned type
The maximum value will expand
Let them all +1 and then an out of bounds will occur
integer literal
Decimal, Hexadecimal, Octal
cout defaults to the decimal output of the output
switch cout
Then there are various bases
How C++ determines the type of a constant
suffix can be added
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
enter a character
cin and cout
It can be seen that it is 77 and M at the same time
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
Let's call the put function of cout to try
escape character
escape sequence using hexadecimal
bool type
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
一般使用
const int xx = 111;
so good
We only want a certain constant to be implemented in a certain one, we use const
Use const instead of define
3.3 Floating point numbers
E notation
setf()
Force output to fixed-point representation, preventing conversion to E-notation
Force the display of the last six digits
cout prints the last six digits by default
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;
}
There has been a problem here
The back is 0
Because the float precision cannot reach
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
The difference between a and b is 1.0 but the subtraction is 0, the accuracy is reduced
float double precision
How are floating point numbers stored?
Single precision 32bit
double double precision 64 bit
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
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
#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;
}
Obviously, it is wrong to add
The number of digits will keep increasing
Floating point numbers must be converted to binary, and decimals are always × 2
Comment out this line, that's right
After rounding, it will be correct. Before, it was mandatory to display the last six digits
Addition, subtraction, multiplication and division will have this problem
float type, really not
We're going to use the double type
integer division
Upcast data type
The number of digits is lengthened, and it is converted to double type division by default
If it is forced to float, add an F
Composite type
4.1 Arrays
Arrays store the same data type
The contents of the array are arranged consecutively in memory
These three points must have
short months[12]
声明通用通用格式
typeName arrayName[arraysize]
What must be stored in it is a constant
The numbers in the array start from 0~
The programmer must confirm that the array subscript does not cross the boundary
#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
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;
}
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++11
This problem can be avoided by providing an initialization list.
#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;
}
The default is 0
Significant bit reduction is not allowed!
that is narrowed
Double is not allowed in long
Array alternative to vector
string
One is, C language style, store the string in the array
The second method based on the string class library
string to \0
end with
The first one is not a string
The first is a character array
He will automatically add \0 compiler added
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
15 bytes
strlen string length ignores \0
The second input is gone
we added a space
cin uses whitespace characters (space, carriage return, tab)
determine the string
he thinks the present is over
dreeb will be stored in the buffer
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()
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;
}
get()
Like getline, it is all about receiving lines
get will discard the newline character and end when it encounters a newline character
It will jump twice directly after entering
empty character, no input
Accept a carriage return in the middle
function overloading
Different parameter lists with the same parameter name
Introduction to the string class
The string can be manipulated by the type of the array, subscript and the like can be
Assignment, splicing, appending
You can assign a string object to another string object
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;
}
strcp(charr1,charr2)
copy
sstr1+=""
strcat(car,“juice”);
z string concatenation
string class I/O
How to use getline to read a large string, stored in string
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()
cin.getline
and
getline
Structure settings
Allow declaration of structure to omit struct
Commas are required when padding
external declaration, visible in all
perk is visible inside the main function
The same structure type can be directly assigned
Structure and Type Direct Declaration
You can also assign
not recommended
bit fields of a structure
Marks how many bits you have, how many bits
Bit fields are low-level programming
4.5 Union
union is a data format
In the union, choose one of the three, and only one can be used at the same time
very similar to struct
The union length is the maximum length
#include<iostream>
using namespace std;
union one2all {
char ch;
int n;
};
int main() {
one2all num;
cout << "sizeof(num)= " << sizeof(num) << endl;
return 0;
}
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
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
In this case, red, orange, etc., all become constants
Each value inside is an integer, starting from zero
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
Can be converted to int such as 0 1 and the like
low to high
Enumerated types, in order to define constants, not create new constants
set enumeration value
Like knowing integers
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)
4.7 Pointers and free memory
Where is it stored?
What is the value,
What type of information is stored
Ask for his worth address,
Add an address symbol
How to declare a pointer
Put the address in the pointer
#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;
}
4.7.2 Dangers of pointers
His address is not clear, there will be bugs in sending values to the address
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
int *pn = new int
;
typeName * pointer_name = new typeName
#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;
}
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
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
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
int * psome = new int [10];
Free the array:
delete [] psome;
without square brackets
Only the first element is released
Pointers are variables, array values are constants
Arrays cannot be added/operated, etc.
pointers, arrays, pointer arithmetic
Dynamic and static binding of arrays
use new[]
No allocation
pointers and strings
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
prevent overflow
new char array
Dynamically open up space
new dynamically creates a structure
better than compile time
structure type pointer
This can also be achieved
Receive dynamic string to open up space function
type combination
Array Alternatives
template class vector
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;
v
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
cycle
In this way without parentheses, he will separate the two sides with an equal sign
do not know
output like 0 1
output of factorial
Chapter 8 Exploring Functions
C++ intrinsics
In order to improve the program running speed
run fast
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
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
Create reference variable
rats and rodents are interchangeable
There is a difference between references and pointers
Use references as function arguments
It's a matter of formal parameters and actual parameters.
Formal parameters manipulate arguments,
out of C language
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?
Function overloading, you can also use function templates
The c++ function template feature can automate this process
template <typename anytype>
almost the same as class
Optional type name
For convenience, T is generally written to save trouble
Any type can be accepted~
Two replacements, either template function or function overloading
#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
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
#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
Exchange structure, directly exchange everything
I just want to exchange money,
Overloading, parameter type, number need to be different
8.5.3 Explicit reification
template <> void Swap(job &j1,job &j2)
tell the compiler. If the job type is passed in, you cannot use other templates
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
Choose the appropriate function call yourself
We define a template function and a non-template function
Non-template functions take precedence
#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;
}
In this way, template functions are preferred
#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;
}
Tell the template function that the parameter is forced to int
compile separately
A project may contain many source code and header files
Except for inline functions, other definitions do not put header files
You can write .c .cpp specifically to call other
Put those things in the header file
One function, one cpp is more fragrant
Take the two apart, compile, and link
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
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
Formal parameters, actual parameters, and the area of parameters, c has learned
Using auto in C++11
register auto
extern
Declare the function, indicating that this parameter is foreign, just want to use it here
Scope Resolution Operators
::
After adding, it is equivalent to calling a global variable
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
Internal only for internal files,
Proximity principle, almost~
file1.cpp
file2.cpp
unlinked local variables
Other functions, files, can't see you
cin.get() Get content
total is only called for the first time. count will drop the initialization bit 0 once
The total value will not change after
specifiers and qualifiers
auto automatically matches the variable type
register allocates memory to a register
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
language linkage
C language one name one function
There may be multiple functions with the same name in C++
Compiler may change his name
Storage schemes and dynamic allocation
new opens up, delete releases
Initialize with new
Open up memory space, the initial value is 6
positioning new operator
You can specify where to store
use new
Handles the hardware accessed at a particular location i or creates an object
specified in that memory space,
specified in buffer1
new positioning operator, requires new header file
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
Obviously, the two addresses are different
We found that pd2 is the same as buffer
when delete
delete cannot be used with the positioned new operator
delete deletes dynamic memory, dynamically releases memory, and new also
9.3 Namespaces
Libraries from different manufacturers may conflict~
9.3.2 New namespace features
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
new name, just add
Of course, the scope resolution operator is required
named
using declaration and using pragma
into the local declaration area
compiler directive
If you use fetch, local variables will be prioritized and there will be no conflicts
Application of namespace
Such using compilation instructions
unnamed namespace
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
Only through public can change private
Control access to members, public or private
Without private, the data is private by default.
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
Use :: to identify the class
We can define the same function with another
Within the class, no need to specify
inline method
Functions defined in the class declaration will automatically become inline functions
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
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;
}
Sell too much, prompt, can't sell
class constructor and destructor
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
If you use default parameters, fill in the value directly in the declaration here (default value)
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
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;
}
If the parameter is passed, it must not be the default constructor
The third, the default constructor
10.3.4 Destructors
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
Destructor has no parameters
~Stock();
At the same time, because the last one has no new, the destructor is empty
10.4 The this pointer
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,
tips
*this represents the entire calling object
The return here is*this
The this pointer points to the object of the calling member
10.5 Arrays of Objects
The constructor initializes the array