C ++ learning stage summary (1)

Some off topic

        Learning new things should still be summed up in time, otherwise they will soon be forgotten. And in the process of summing up, we will sort out our own language and thinking, and also improve our personal expression skills. Sticking to doing simple things is not easy, come on girl ~

        I started learning C ++ in July. At that time, I participated in a competition related to digital image processing and machine learning. A lot of excellent code was written in C ++, but I could n’t understand it, and there was no way to improve it. The result of the game was terrible. So I am determined to learn this magical and efficient programming language ~ On the other hand, I am also preparing for the job search. After all, object-oriented programming is a great programming technique. Learn this systematically. Thinking, in the future, it can also be used consciously to solve practical problems in other programming languages ​​(such as MATLAB, Python).

        I have finished reading Larry Ullman, Andreas Signer's "C ++ Book for Everyone", and part of Guan Hao and An Zhiyong's "C ++ is no longer difficult to learn-fast customs clearance with old birds". Looking at the titles of these two books, you know that it is an introductory reading tailored for people with zero foundation. But getting started is really important! ! ! At the beginning, you don't need to worry about some details, but you should focus on understanding programming ideas. Of course, the basic hands-on ability is still necessary, so don't be lazy, the programming ability is practiced ~  

        The following is a summary of the newly learned things for future reference.

text

        

1 Preparation

      In the process of programming, we may encounter many problems. When we are unable to solve them, we often think of turning to some search engines or technical forums. How to ask questions effectively is also an art. See "How to Ask Questions the Smart Way" (http://catb.org/~esr/faqs/smart-questions.html) written by Eric Steven Raymond for details.

       Writing a program in C ++ generally requires multiple steps: clear the purpose and needs of this program-> programming-> compile, link-> (debug, debug, debug ...)-> compile, link-> run . Choosing an IDE that suits your own integrated development environment can greatly improve the efficiency of programming. I use Dev-C ++.



2 Data type, basic syntax, control structure

         Common data types are integers, real numbers, arrays, characters, strings, pointers, structures, and unions;


        C ++ has stricter grammar requirements for the program. Missing a small semicolon and asymmetry in parentheses will report errors, so you must develop good programming habits and try to avoid making some low-level errors;

        Be sure to declare or define before using variables and functions;

        The type and scope of variables should be carefully considered, and the code should be optimized as much as possible under the premise of completing basic functions;

        

       The control structure includes conditional if (-else), ternary operator (? :), multiple conditions (switch), loop (while, for);


  

3 input, output and files

        The essence of each program is to process data, and a lot of data requires user input or reading from a file. After processing, the result needs to be displayed, and it needs to be output to the interactive interface or saved as a file.

        Be sure to check the legality of the input data; when you need to enter the data multiple times, remember to delete the residue of the buffer;

        When reading and writing files, be sure to check whether the file is actually opened;



4 define personal functions

        Create a function with input parameters The values ​​passed to the function must have the correct type and order; when defining the function, all mandatory parameters must be placed before optional parameters;

        The inline function does not need to define a prototype for it, the entire function is defined before the main function;

        The overload of a function is to define a function with different parameters (which can be of different data types or with a different number of parameters) with the same name, but with the same purpose;

        There are several types of function call: transfer by value, transfer by address, and transfer by reference;


5 objects and classes

     (Routine 1

#include 
#include 
//基类 
class Pet{
public:
	Pet(std::string theName);
	~Pet();
	virtual void eat();
	virtual void sleep();
	virtual void play()=0;//虚方法 //=0抽象方法   如果一个类中有一个抽象方法,那么必须至少还有一个普通的虚方法 
	static int getCount(); //静态方法 
	//void setName(std::string theName);
protected://允许这个类和他的子类来访问以下属性和方法 
	std::string name;
	friend class PetRenamer;//友元关系声明 (应该在没有其他办法时才使用友元关系,友元关系太多往往表示设计方案有缺陷)
private:
    static int count; //静态属性 
};
Pet::Pet(std::string theName){
	name=theName;
	count++;
	std::cout<<"Creating a pet named '"<name;
	std::cout<<" to "<name=newName;
	
}

//子类1 
//继承时的保留字public、protected、private与类的声明中含义不同 
class Cat:public Pet{
public:
	Cat(std::string theName);
	void climb();
	void play();
};
//继承机制中的构造器 
Cat::Cat(std::string theName):Pet(theName){
}
void Cat::climb(){
	std::cout<sleep();
	cat->eat();
	cat->play();
	std::cout<<"\n";
	dog->sleep();
	dog->eat();
	dog->play();
	
	delete cat;
	delete dog;
	return 0;
}

       primary

       Object programming is the core of C ++. We can understand the object as a new data type, the difference is that it includes not only variables (attributes) but also functions (methods).

       In the declaration of the class, usually one of the three reserved words public, protected, private needs to be added in front of the attributes and methods to control its accessibility;

       Methods can call each other;

       Constructors and destructors are a special kind of method;

       this pointer

       intermediate

       Class inheritance mechanism : This mechanism allows programmers to create a class hierarchy, and each subclass will inherit the methods and properties defined in its base class. In other words, the existing trusted code can be extended through the inheritance mechanism, greatly improving development efficiency.

       Pay attention to the syntax of the constructor and destructor used in the inheritance mechanism;

        In some cases, the override method needs to provide a general function in the base class, but it needs to change the implementation of this method in its subclass;

       The overloading method  is the same as the function overloading;

       Friendship   A completely irrelevant class needs to access a protected member or a private member; the friend of the class is selected by itself, which is stated in the class declaration; do not abuse the friend relationship

       advanced

       Static properties and static methods     do not belong to a single object but belong to the properties and methods of the entire class. Benefits: You can still control their access rights through reserved words; you can access the member without creating any objects; make certain data in Shared between all objects of this class; you cannot access non-static properties in static methods; do n’t forget to allocate memory for static properties (that is, make static property declarations outside the class declaration);

       A virtual method    overloads a method in a subclass, but when a subclass object is generated by the new method, a pointer to the base class is used. When the method is called, the method in the base class is still called. It is easier to see the routine. Understand that declaring all methods as virtual methods in the base class will slow down the final executable code, but can ensure that the program behaves as expected. When implementing a multi-level class inheritance relationship, the topmost base class should only have virtual methods.

       Abstract methods  tell the compiler that this method is indispensable, but I cannot provide an implementation for it now (in this base class); to use abstract methods, you must implement it in the base class; there is one more detail to note: if To use abstract methods in a class, it must have at least one ordinary virtual method;

       Polymorphic  functions that can handle many different data types

       The  purpose of the overloaded operator is to make the code easier to read and understand, try not to lose its original meaning; declared before the main function, implemented after the main function;

       More than    one subclass inherits two or more base classes;  

       Virtual inheritance    tells the compiler that subclasses derived from the current class can only have one instance of that base class


6 Dynamic memory management

        Dynamic memory allows programmers to create and use various data structures that can be expanded or contracted according to specific needs; another use is for functions to return a pointer to a memory block (factory function);

        Dynamic memory consists of memory blocks with only addresses and no names, so you must use pointers to access them. Although dynamically allocated memory blocks have no scope, pointer variables used to store their addresses have scope.

        Application and release of dynamic memory; the delete statement only releases the memory block pointed to by the pointer, but the pointer is still there;

        Don't forget to declare methods as virtual methods when creating and using objects dynamically;

        Copy constructor and assignment operator Application occasions-> Two objects are copied, but they contain pointer type members. Copying bit by bit will cause pointer hidden danger. As long as you declare a class that has a pointer attribute and will release that memory in the destructor, you need to implement a copy constructor and assignment operator; you must ensure that the copy constructor copies all attributes. Static object coercion / dynamic object coercion is best to always use the dynamic_cast operator when dealing with objects, remember to check whether the result is NULL before moving on  


7 Namespaces and modularity

        Header files are divided into system header files and custom header files to save function declarations, user-defined data types (structures and classes), templates, and global constants; only include the most necessary code; try to avoid using them when importing Absolute path, because this will reduce the portability of the code;

        Implementation files For users, see the header files to understand the basic usage of functions, etc. For the compiler, it needs to be cleared until how each function or class is implemented; the name of the implementation file should be consistent with the header file;

        C preprocessor is a tool created by people to develop C applications and speed up their execution.

        The namespace is defined by the user himself. The things in the same namespace can be unique in this namespace; you can use the namespace keyword to add new things to a namespace in the same or another file; use Namespace using thing (do not write anything, do n’t just write the name of the namespace, although this is not impossible), the location of the using directive or declaration determines in which scope the things extracted from the namespace can be used;

        The three concepts of link, scope, and storage class are interrelated, but the angle of observation and description of the problem is different ~ When multiple files are compiled at the same time, each file is called a translation unit, and in each translation unit Whether and how the defined things are used in another translation unit is where the link comes into play; it is divided into external links (each translation unit can be accessed as long as the variable exists), internal links (in a translation unit The defined things can only be used in the translation unit) and no connection (the variables defined in the function only exist inside the function). Each variable has a storage class, which determines where and how the program will store the value of the variable on the computer, and what scope the variable should have.


8 templates

         C ++ programming paradigm: procedural paradigm (divide the program into different functions), object-oriented paradigm (organize code and data into various classes and establish inheritance relationships between classes), generic programming (Support programmers to create templates of functions and classes, rather than specific functions and classes, you can solve multiple problems with one solution ~)

         Write and use your own generic code function template (do not divide the function template into prototype and implementation); class template (same as above); use inline notation to avoid the compiler from finding the implementation and make the program readable higher;

         Standard template library STL

         Containers and algorithm containers are numerical structures that can hold two or more values. Different problems are suitable for different containers. You can write your own, or you can call the C ++ Standard Template Library (STL). There are many carefully designed and tested Ready-made containers; finding the most suitable container is only a part of the programming work, and some functions (algorithms) are needed to process the data in that container. STL also provides many well-conceived and strictly tested algorithms to solve various common problem. Details of commonly used algorithms in STL can be found online.




          The above is most of the content in the first reference book. After mastering these basic concepts, you can write simple C ++ applications. But many details are not noticeable before you do it yourself, you still have to do more ~

       

Released nine original articles · won praise 1 · views 6066

Guess you like

Origin blog.csdn.net/wcysghww/article/details/77966136