c++ Learning Notes 1

c++ Learning Notes 1

I am a beginner of c++. I have made some notes for you to refer to and review.
I listened to Mr. Weng Kai's class on Station B. Mr. Weng Kai's class is very good. You can listen to it if you are interested.
Sometimes I compare C with c++ because I have a base in C.
//

#include <iostream>
#include <stdlib.h>
using namespace std;  //Namespace

int main()
{
	cout << "hello world"<<endl;
	system("pause");
	return 0;
}

This is a c++ template starting with #include <io. H>, c++ is #include. To use std, add #include <stdlib. H>. STD is a class (input-output standard) that includes cin members (standard input) and cout members that can only be used after using name space std. Otherwise write as std cout. The output format is similar to that shown above, but ">" is used. system(); Is the header file <windows. H>A function in the library. Called the command line of the system, such as: system("clr"); To clear the screen, you can also delete experimental files, format disks and other DOS, command line commands...
///

class Point3d{
public:
    Point3d(float x,float y,float z);
    print();	
private:
    float x;
	float y;
	float z;		
};

c++ is bound to use classes, the above is the format of classes, classes are defined by classes, and publics are public; Private is private, and the variables inside are called member variables.
Point3d a(1,2,3);a is an object of class
a.print(); This is the function that is calling the object
Class declarations are placed in. In the h file, the definition of the function in the class is placed. Inside cpp file
C++ classes are similar to C language struct, but more powerful than struct. Of course, c++ can also use struct (the difference between struct and class will be mentioned later), so c++ is an extension of C language.

#ifndef TIC_H_
#define TIC_H_

class Tic{
public:
	Tic();
	virtual ~Tic();
	void showPrompt();
	void inserBalance(int money);
private:
    //const int price;
	int balance;
	int total;
	int i;
};

#endif

This is. Format of h file

#include "Tic.h"
#include <stdio.h>
#include <iostream>
using namespace std;

void Tic::showPrompt()
{
	cout << "something";
	i=20;
	printf("Tic::showPrompt()--&i=%p\n",&i);
}

void Tic::inserMoney(int money)
{
	balance += money;
}

This is. Format of cpp file
:: f(), global.:: Is a parser.
Note that member variables are in the object of a class, not in that class; c++ can use libraries in the c language, but printf cannot be mixed with cout in one program.

class X{
	int i;
public:
    void f();
	void grow(int b);
    X();	//Constructor contructor (called when an object is created) (no return type) (can be used to initialize) 
};

int main(){
	cout<<"hellor"<<endl;
	{
		X a(10);//Default call to constructor, 10 input to constructor
		cout<<"hellor"<<endl;
		a.f();
		a.grow(4);
		cout<<"hellor"<<endl;
	}//Curly bracket means a does not exist
	cout<<"hellor"<<endl;
}

The properties of member variables are not defined in class X above because there are no access properties (private and public) for classes in c++, defaulting to private, and defaulting to public for struct.
The usage of {} is described above. Objects are created inside {} and braces do not exist.
With classes, you must know that the constructor and destructor, and the function X() with the same name as the class, are constructors. It does not return a type, and the constructor is called automatically when an object is created, so it can be used as initialization.

 class Y{
public:
    ~Y();  	//destructor (called when an object is destroyed) (no return type)
	Y();
	void f();
 };
 
Y::~Y(){
	cout<<"hellor"<<endl;
	 printsize();
};

int main(){
	cout<<"hellor"<<endl;
	{
		Y a(10);//Default call to constructor, 10 input to constructor
		cout<<"hellor"<<endl;
		a.f();
		cout<<"hellor"<<endl;
	}//Curly brackets indicate that a does not exist (the destructor is called at this time)
	cout<<"hellor"<<endl;
}

The destructor is based on the constructor with a small wave, ~Y(). The destructor also has no return type and is called automatically when the object is destroyed.
///

struct X{float f; int i;};
X a[3]={{1.1},{1}};
struct Y{float f; int i; Y(int a);};//(struct is similar to class) Y(int a) is a constructor
Y b[]={Y(1),Y(2),Y(3)};

The constructor without parameters is called default constructor.
An object cannot be destructed without being constructed.
There can be functions in struct in c++.
//
new int;new int[10];
delete p;delete []p; Destruct before taking back space
new,delete is equivalent to c++ versions of malloc and free
int * psome=new int [10];
delete [] psome; ([] means PSome has a lot of space, just delete the first one if you don't want to)
Matters needing attention:
Do not delete to free space that is not allocated by new. Do not use delete to free the same space twice. New band [], delete band [], delete delete to null pointer is safe.

class A{
private:
    int i;
	int *p;
public:	
	A(){p=0;i=0;cout<<"A::A()"<<endl;}
	~A(){if(p) delete p;cout<<"A::~A(),i="<<endl;}//delete Delete to null pointer is safe
    void set(int i){this->i=i;}//This->i refers to the object I of the class, not the parameter I (this will be discussed later)
    void f(){cout<<"hellow";}	
};

//

struct X;//Forward Declaration (with X)
struct Y{
    void f(X*);
};

struct X{
private:
    int i;
public:
    void initialize();
    friend void g(X*,int);
    friend void Y::f(X*);
    friend strucu Z;
    friend void h();	
};

Friend makes the class or function a friend class or function. Private properties and methods that are not normally accessible can be accessed externally. There is a book about this: C++ encapsulation is like a wall, which can ensure the safety of the things inside the wall. Friends are like having a door on a wall through which you can enter and use what's inside. This may be convenient in some cases, but it breaks the C++ encapsulation, so be careful.
If structure X is behind structure Y and Y uses X, a forward declaration can be made.
In c++, there are no access properties (private and public) for the class, defaulting to private, and defaulting to public for struct.
/

class Point{
private:
    const float x,y;
	Point(float xa=0.0,float ya=0.0):y(ya),x(xa){});//y(ya),x(xa) is an assignment and is initialized before the constructor when placed outside curly braces
}

Assignment outside braces is initialization and inside is assignment.
//

class Person{...};
class Currency{...};
class SavingsAccount{
public:
    SavingsAccount(const char* name,const char* address,int cents);
    ~SavingsAccount();
    void print();    
private:
    Person m_saver;
    Currency m_balance;	
};

SavingsAccount::SavingsAccount(const char* name,const char* address,int cents):m_saver(name,address),m_balance(0,cents){}//Initialization is placed outside braces (all initializations must be placed here, and the parent must be placed here)

SavingsAccount::print(){
    m_saver.print();
	m_balance.print();
}

Object Composition (Composition is the assembling of existing objects into a new object), above which is the object composition.
Normally, we place initialization outside the braces of the constructor, and then we'll talk about the concept of parent-child classes, which are also outside the braces of the subclass constructor.
//
Inheritance (Modifying an existing class to a new one)

class A{
public:
    A():i(0){cout<<"A::A()"<<endl;}
    ~A(){cout<<"A::~A()"<<endl;}    
	void print(){cout<<"A::print()"<<i<<endl;}
protected:	
	void set(int ii){i=ii;}//protected property can only be called by itself and by subclasses
private:
    int i;	
};

class B : public A{            //B is a subclass of A
public:
    void f(){
	          set(20);
		    }    
};
int main()
{
    B b;
	//b.set(20); This is wrong
	b.print();
	b.f();
	return 0;
}

Const std:: string & name (name is defined as the protected attribute).
As shown above, when an object of a subclass is constructed, the constructor of its parent class is automatically called, with the parent class preceding the subclass and the subclass preceding the parent destructor. Initialization of the parent class should be placed in the constructor of the subclass, that is, the parameters required by the parent constructor should be placed outside the braces of the subclass constructor. The protected property can only be called by itself and by subclasses, so b.set(20) in the main function above; Is wrong.

class A{
public:
    A():i(0){cout<<"A::A()"<<endl;}
    ~A(){cout<<"A::~A()"<<endl;}    
	void print(){cout<<"A::print()"<<i<<endl;	
	void set(int ii){i=ii;}//protected property can only be called by itself and by subclasses
private:
    int i;	
};

class B : public A{            //B is a subclass of A
public:
    B():A(15){cout<<"B::B()"<<endl;}    //A constructs B first, then B destructs
	~B(){cout<<"B::~B()"<<endl;}
    void f(){
	          set(20);
		    }    
};
int main()
{
    B b;
	b.set(20);
	b.print();
	b.f();
	return 0;
}

If there are several identical functions in c++, the compiler will determine which function to call based on the number and type of parameters you give.
cout is the c++ built-in output stream ostream. You can customize your own output stream, either ostream or ofstream. Many programs like to use the name out because out stands for output.
We should try to make the best use of the code we've written, instead of letting the same code be everywhere in the program and avoiding code duplication.

class Employee {
public:
    Employee(const std::string& name,const std::string&ssn);
    const std::string& get_name() const;	
	void print(std::ostream& out) const;
	void print(std::ostream& out, const std::string& msg) const;
protected:
    std::string m_name;
	std::string m_ssn;
};

inline conet std::string& Employee::get_name() const {
  return m_name;
}

inline void Employee::print(std::ostream& out) const {
  out << m_name << endl;
  out << m_ssn << endl;
}

inline void Employee::print(std::ostream& out, const std::string& msg) const {
  out << msg <<endl;
  print(out);
}

class Manager : public Employee {
public:
    Manager(const std::string& name,const std::string&ssn,const std::string& title);
	const std::string title_name() const;
	const std::string& get_title() const;
	void print(std::ostream& out) const;
private:
    std::string m_title;	
};

/
Employee::Employee(const string& name,const string& ssn) : m_name(name),m_ssn(ssn) {
  //initializer list sets up the values!
}

For c++, if one of the functions in the parent has several different forms, and there are duplicate functions (the same name, the same parameter table) in the subclass, then only one of the subclasses has its own function, and all of the subclasses are hidden. (This happens in other languages where these functions are related, that is, "You're my substitute," and in c++, they're not).
Return types cannot form conditions for parameter overloads. That is, the function name is the same, the parameters are the same, but the return values are different.

Function default parameter values
int harpo(int n,int m=4,int j=5);// (You can take arguments here) (This is written in.h, not in.cpp, or directly in the main function to write the function prototype with parameters)
int chico(int n,int m=6,int j);// This form is wrong
With parameters must start on the right.
beeps=harpo(2);
beeps=harpo(1,8);
beeps=harpo(8,7,6);
We can take parameters inside a function, that is, we can assign a value to a function parameter when it is defined, and then we can give a value without assigning a value to a parameter that has already been assigned. Write with parameters in. h inside, not in. Write it again in cpp, otherwise it will cause duplicate definitions, or you can write out the function prototype with parameters directly in the main function. Of course, this method is only mentioned here and is not commonly used. It is not safe.
//
Inline function: An inline function is preceded by an inline function, which is called by embedding the code of the function in the place where it is called, but preserving the independence of the function in order to reduce the extra work.
Because the compiler performs a series of operations, such as stacking and stacking, which adds a lot of extra work, to reduce the extra work, we add inline before the function.
Inline is in. h and. cpp must repeat that the body of the function is to be placed. h file, then there will be duplicate definitions. After inline is added to the function, it is no longer a definition but a declaration. So inline should not have. cpp file, everything in. h File inside.
inline is really about sacrificing code space to reduce the extra overhead (space for time) of calling functions.
inline is safer than macro definitions in c. Macro definitions cannot do type checking. inline can be used as a function for type checking by the compiler.

#define f(a) (a)+(a)
main(){
  double a=4;
  printf("%d",f(a));
}

inline int f(int i){
  double a=4;
  printf("%d",f(a));
}

The code here, the last one is C language, the last one is c++, where the C language code is wrong, it is double, but the output is int, but it deceives the compiler, does not make a mistake, chops 64 bits into 32 bits to get an incorrect result, and the c++ code will prompt you if you need to force a conversion.
Be careful:
1. Recursion requires entering and exiting villages, inline is not allowed.
2. When the inline function is too complex, the compiler may reject this operation.
3. If a member function is defined when it is declared, then this function is an inline, and this class only has one. h is enough.

class Point{
  int i,j,k;//(private by default if no properties are defined)
public: 
    Point(){i=j=k=0};
	.........
};

You can also put the definition of the function after the class, preceded by inline. Make the class look refreshing.
If a function is called relatively small or frequently, you can make it an inline; very large (over 20 lines) or recursive functions do not use inline.
/
const
Const variables cannot be assigned or modified after initialization. This const variable is still a variable, not a constant, for c++, because it means you have to assign an address in memory.

const int class_size=12;
int finalGrade[class_size];//OK

int x;
cin >> x;
const int size=x;
double classAverage[size];//error

The error here is because the compiler needs to know how big the local variable is and then allocate memory to it.

There are two cases when a pointer encounters a const
One is q is const, the other is *q is const

char *const q="abc";//q is const
    *q='c';//ok
	q++;//error
	
const char *p="ABCD";//*p is const char
    *p='b';//Error (meaning that you can't modify the memory unit I specified with this p, instead of where I refer, that memory unit becomes const)
	
Person p1("Fred",200);
const Person* p=&p1;	//Object is const
Person const* p=&p1;	//Object is const
Person *const p=&p1;    //Pointer is const

See if const is before or after the * sign (or if you add a const before it, the pointer and the object are both const)
*p means const. You can't use this p to modify the memory unit I specify, not where I refer, and that memory unit becomes const.

int i;
const int ci=3;
int *ip;
const int *cip;
ip=&i;
cip=&i;
ip=&ci;//error (can modify what he refers to through ip, but ci is const and is not allowed to be modified)
cip=&ci;

int main()
{
char *s="hellow world";// There will be woring and const should be added at the top. If this is char s[]= "hellow world", then this program is correct because it copies the "hellow world" from the code snippet to the stack
cout << s << endl;
s[0]='B';
cout << s << endl;
return 0;
}
This is incorrect. Local variables are on the stack, global variables are in the global data area, and the constant hellow world in global variables is in the code snippet, which is not writable. This is a const and cannot be modified.

Void f(const int*x);// You can give an int or a const int to this function, which guarantees that the parameter will not be modified within the function.
int a=15;
f(&a);//ok
const int b=a;
f(&b);//ok
b=a+1;//error
If the parameter of the function is const int x, it doesn't matter to the person calling f, because it's not a pointer, it just means that x is not changed inside F.

int f2(){return 1;}
const int f3(){return 1;}
int main(){
const int j=f2();
int k=f3();// Because this is an assignment, it does not modify the return of f3().
}
All these operations are possible

const Currency the_raise(42,38)//The entire object is const, and the values inside this object cannot be modified. We need to know which functions in this object can be executed and which cannot be executed.
int Date::get_day() const {
...
}
We can add const to the end of a function, which means that the function does not modify any member variables (const is required where the prototype and definition are concerned).
int get_day() const; // In fact, this is const.

About this:
Each object has a this pointer, which records the memory address of the object. When we call a member function, the default first parameter of the member function is T* const register //this. Most compilers pass this pointer through an ecx register, and the data member of the object can be accessed through this implicit parameter.

Why can't a member function of a class be decorated with both static and const?
Functions decorated with const in a class are usually used to prevent modifying the data members of an object. The const at the end of a function is used to decorate the this pointer to prevent modification of the data members within the function. Static//functions do not have this pointer to access the data members of the object and conflict with C++ static semantics, so they cannot.

this Pointer Attention Point
1. The this keyword in C++ is a constant pointer to the object itself and cannot be assigned to this.
2. Only member functions have this pointer. Friend functions are not member functions of classes and have no this pointer.
3. Similarly, there is no this pointer for a static function, which is not a specific object, just like a static variable.
4. The this pointer scope is inside the class member function and cannot be obtained outside the class.
5. The this pointer is not part of the object. The memory size of the this pointer is not reflected in the sizeof operator.

Use of this pointer
1. When returning the class object itself in the class's non-static member function, use return //this directly, such as the class's default addressing operator overloading function, or return a reference to this, which can be "cascaded" like input-output streams;
2. When modifying a class member variable or parameter with the same name as a member variable, such as this->a = a (written as a = a but compiled);
3. Use the type variable itself when defining a class, because at this time the variable name is unknown, use a pointer like this to use the variable itself.

this was created in the process of object new

This is my first stage of learning notes, there is still a lot of content in c++, waiting for me to learn and accumulate slowly. When I came into contact with c++, I found that my previous view of programming was too narrow, which really increased my horizon and the diversity of programming. In fact, a good program tests the programmer's typesetting ability and meticulousness. Learn more and practice is also helpful to improve your proficiency and the application of some potential rules, as well as the speed of code writing. I think it is very important to have good code writing habits and your own style of code writing. I have been copying other people's code, although fast in all senses, but there is no accumulative process. You still can't remember how to play this code next time.
We programmers must pay attention to warning. Don't ignore it because it may run. A piece of code, a project, we may use it many times, and don't make a hole in ourselves because of it. Mr. Weng told a joke in class. A sign was placed in front of the cliff with warning written on it. The programmer would fall down.
Details determine success or failure.

Keywords: C++

Added by pastcow on Tue, 08 Mar 2022 19:32:18 +0200