Like attention, no more lost, your support means a lot to me!
🔥 Hi, I’m Chouchou. GitHub · Android-Notebook has been included in this article. Welcome to grow up with Chouchou Peng. (Contact information at GitHub)
Basic concept
- The namespace
Namespace xurui {int age = 1; char * name = "xurui"; } using namespace xurui; using namespace xurui; Access a member of the namespace: xurui::name or name (omit the namespace :: if there is no conflict)Copy the code
#include<iostream> // C++ library using namespace STD; // namespace, similar to Java's inner class cout<< "C++" << endl; // The reference references the STD :: namespace, so it can be omittedCopy the code
Tip: << is an operator overload
- Bool in C++
C doesn’t have booleans. A bool in C++ is a wrapper around an int.
cout << true << endl; Output: 1.Copy the code
- C and C++ constants
C: false const int number = 100; int * numP = &number; *numP = 10000; printf("%d\n", number); C++ : true const int number = 100; Int * numP = &number; int * numP = &number;Copy the code
- Principle of reference
A reference variable is an alias for another variable that can be accessed using the reference name once the reference is initialized to a variable.
Reference VS pointer
References are easily confused with Pointers, and there are three major differences:
- 1. There are no empty references. References must be connected to a valid block of memory. A wild pointer is an uninitialized pointer and a dangling pointer is a pointer to a memory that has been freed.
- 2. References must be initialized at creation time, and Pointers can be initialized at any time;
- 3. Once a reference is initialized to an object, it cannot be pointed to another object. A pointer can point to another object at any time.
- The default parameters
int add(int n1 = 0, int n2 = 1) {
}
Copy the code
Default parameters can be specified in a function declaration or when the function is defined.
- Variable parameter
The macro | describe |
---|---|
va_list | Argument list pointer arg_ptr |
va_start(arg_ptr, argN) | Makes the argument list pointer arg_ptr point to the first optional argument in the function argument list. ArgN is the fixed argument that precedes the first optional argument |
va_arg(arg_ptr, type) | Returns the argument referred to by arg_ptr in the argument list. The return type is type. And make the pointer arg_ptr point to the next parameter in the argument list |
va_end(arg_ptr) | Clears the argument list. The collimated argument pointer arg_ptr is invalid |
#include <stdarg.h> using namespace std; void sum(int count, ...) { va_list vp; va_start(vp, count); for (int index = 0; index < count; index++) { int number = va_arg(vp, int); cout << number << endl; } va_end(vp); } int main () {/ / output: / / 1 / / 2 / / 3 sum (3, 1, 2, 3); return 0; }Copy the code
- Function overloading: Unlike C, C++ supports function overloading
Note that if you define functions that take default parameters, you need to make sure that there are no overloaded functions with fewer parameters, otherwise an error will be reported: Call to ‘add’ is ambiguous. Such as:
int add(int n1){
return n1;
}
int add(int n1 = 1,int n2 = 1){
return n1 + n2;
}
int main(){
add(1); (X)// Call to 'add' is ambiguous
}
Copy the code
- Operator overloading:
Overloaded operators are functions with special names consisting of the keyword operator and the operator symbol to be overloaded after it. Like other functions, overloaded operators have a return type and a list of arguments.
Student. H: class Student {public: Student operator+(Student Student); }; Student. CPP: Student Student::operator+(Student Student) {return Student(); } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- more strict writing: class Student {public: Student operator+(const Student &student); }; Note: If the & is not used, the function call builds an additional copy of the object (copy constructor) Student Student::operator+(const Student & Student) {return Student(); }Copy the code
Classes and objects
- Specification for class declarations
Class members are declared using the.h header and implemented using.cpp. This is the C++ class definition specification. The goal is that when you expose the so library, you just need to provide the client with the.h header file to invoke the implementation in the so library.
- Class declarations
Student.h
Class Student {// Private member private: char*name; int age; };Copy the code
- The implementation class
Student.cpp
class Student { public: char *getName() const; void setName(char *name); int getAge() const; void setAge(int age); // Private member private: char*name; int age; };Copy the code
Student.cpp
char *Student::getName() const { return name; } void Student::setName(char *name) { Student::name = name; // this->name = name; } int Student::getAge() const { return age; } void Student::setAge(int age) { Student::age = age; // this->age = age; }Copy the code
Tip: On the Student. CPP editing page, press Alt+ Insert to automatically insert functions such as setters/getters
- Static and dynamic development of objects
Static open: stack Student Student; // The constructor student.setage (10) is not called; student.setName("mark"); cout << "name:" << student.getAge() << ",name:" << student.getName() << endl; Student * Student = new Student(); Student * Student = new Student(); // The constructor student->setAge(10) is called; student->setName("mark"); cout << "name:" << student->getAge() << ",name:" << student->getName() << endl; if (student) { delete student; // delete student = NULL; // free(student); // (X) malloc allocates space free}Copy the code
Note: New allocates space with delete, malloc allocates space with free. Malloc does not call the constructor, and free does not call the destructor.
- Constructors & destructors
Declare class Student {public: Student(); Student(char*name); ~Student(); }; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / calls another overloaded constructor Student: : Student () : Student("mark") { } Student::Student(char *name) { this->name = (char *) (malloc(sizeof(char) * 10)); strcpy(this->name, name); } Student::~Student() {if (this->name) {free(this->name); this->name = NULL; }}Copy the code
Tip: New calls the constructor and DELETE calls the destructor.
- Copy constructor
1. When no constructor is defined in a class, the compiler provides a null constructor with no arguments by default. When a class does not have a copy constructor defined, the compiler provides one by default for copying member variables. This copy operation is a shallow copy. Call constructor once, call default copy constructor once (shallow copy), pointer members of both objects refer to the same block of memory. The destructor is called twice and the memory space is freed repeatedly causing a crash.
Student* student1 = new Student(); Student* student2 = student1; Case 2: implicitly call the copy constructor Student student1; Student student2 = student1; Student student1: the default copy constructor is called instead of the custom copy constructor. Student student2; student2 = student1;Copy the code
Tip: Structs have similar shallow copies.
- Static members
Static member (field/function); static member (field/function); Static members can only access static members.
Student.h
Class Student {public: 1, static int id; static void update(){ id = 2; }};Copy the code
Student.cpp
Int Student::id = 1;Copy the code
Student student; cout << student.id << endl; Student::update(); cout << student.id << endl; Output: 1 2Copy the code
- A friend function
A friend function is a function declared in a class and implemented outside the class. A friend function is not a member function, but it can access a private member of a class. Friend functions break class encapsulation to some extent.
Student.h
class Student {
public:
friend void setAge(Student * student,int age);
private:
int age;
};
Copy the code
main.cpp
void setAge(Student *student, int age) { student->age = age; } int main() { Student student; setAge(&student, 1); // 1 cout<< student.getage ()<<endl; return 0; }Copy the code
- Friends metaclass
All member functions of a friend class are friends of another class and have access to hidden information (both private and protected members) in another class.
class ImageView { private: int viewSize; friend class Class; // friend class}; class Class { public: ImageView imageView; void changeViewSize(int size) { imageView.viewSize = size; // if you do not declare "friend class class", you cannot access}};Copy the code
In Java, private members cannot be accessed directly, but can be accessed using Class#getDeclareField(). Is the underlying principle C++ friend classes?
- inheritance
class Rectangle: public Shape, public PaintCost { public: int getArea() { return (width * height); }};Copy the code
Multiple inheritance is ambiguous and can lead to less robust programs, so Java design does not support multiple inheritance. In C++, because of multiple inheritance, program ambiguity is actively avoided during development. If ambiguities already occur, there are two solutions: 1. Explicit access can be used to circumvent ambiguities using class names :: variable names; 2. Use virtual inheritance.
- Derived types
When a class is derived from a base class, the base class can be inherited as public, protected, or private. Using public inheritance, different inheritance type rules:
Public: When a class is derived from a public base class, the public members of the base class are also the public members of the derived class. The protected members of the base class are also the protected members of the derived class. The private members of the base class cannot be accessed directly by the derived class, but can be accessed by calling the public and protected members of the base class. Protected inheritance: When a class is derived from a protected base class, the public and protected members of the base class become protected members of the derived class. 3, private inheritance (private) : When a derived class has a base class, the public and protected members of the base class become the private members of the derived class.
- Virtual inheritance
In order to solve the problem of naming ambiguity and redundant data in multiple inheritance, C++ designs virtual inheritance so that only one member of the indirect base class is kept in a derived class.
// indirect base class A class A{protected: int m_a; }; Class B: virtual public A{// virtual inheritance protected: int m_b; }; Class C: virtual public A{// virtual inherited protected: int m_c; };Copy the code
- polymorphism
C++ turns polymorphism (or static polymorphism/static linking) off by default: function calls are determined before the program is executed. To enable polymorphism, you need to declare virtual (virtual function) on the superclass function.
- Pure virtual function
C++ interfaces have no direct concept of abstract classes/interfaces, but you can use pure virtual functions to achieve similar semantics. Pure virtual functions are declared as follows:
virtual void funtion1()=0;
Copy the code
Pure virtual functions are used to regulate the behavior of derived classes, i.e. interfaces. Pure virtual functions must not be defined. Classes that contain pure virtual functions are abstract classes that cannot define instances, but can declare Pointers or references to concrete classes that implement the abstract class.
Templates (similar to generics)
- A function template
template <class T> void swap(T& a, T& b){
}
Copy the code
- Class template
template<class T> class A{
public:
T a;
T b;
T hy(T c, T &d);
};
Copy the code
STL containers
class | describe |
---|---|
vector | The dynamic array |
list | The list |
stack | The stack |
queue | The queue |
set | Red black tree, automatic sorting, no repetition |
multiset | Red black tree, auto-sort, with repetition |
map | Red-black trees, ordered key/value pairs, with repetition |
multimap | Red-black tree, ordered key/value pairs, no repetition |
The resources
- Novice tutorial
- C++ Primer Plus by Stephen Prata
Creation is not easy, your “three lian” is chouchou’s biggest motivation, we will see you next time!