Series Notes
  • [Basic Data Structure] ()
  • [Use of classes] ()
  • [Inheritance and derivation of class] ()
  • [One of the object-oriented features polymorphism] ()
  • [Operator overload] ()
  • [Use of const keyword] ()

1. Definition and use of classes

1.1 Definition of Class

The simplest class declaration:
 class Student{ };

The semicolon should be added at the end of the class definition, which is different from Java, otherwise there will be compilation errors.

Use of Class 1.2

That is, create an instance of a class -- an object. In java, you will use new Keyword. In C++, creating objects is as simple as using ordinary data types:

 Student studentObject;

2. Member variables and member functions of classes

2.1 Member Variables

 class Student { char name[20];  // full name Int id_num;//Student ID Int age;//Age Char sex;//Gender

Unlike Java, member variables of a class cannot be initialized when they are created.

2.2 Member Functions

Unlike java, c++member functions can be defined in two ways:

1. Class internal declaration, class external definition (implementation):
 class student { void set_age(int a); int get_age(); }; //Define set_age function outside class void student::set_age(int a) { age = a; } //Define the get_age function outside the class int student::get_age() { return age; }

Declare the function inside the class, and define it outside the class It is implemented through the scope operator::.
When declaring, you only need to write the return type, function name, parameter list, and semicolon at the end, instead of curly braces.

 Return type class name:: member function name (parameter list) { //Function body }

You can also The member function declaration of a class is preceded by the inline Keyword to make it an inline function Inline functions can optimize the execution efficiency of programs.

 class student { inline void set_age(int a); inline int get_age(); }; //Define set_age function outside class void student::set_age(int a) { age = a; } //Define the get_age function outside the class int student::get_age() { return age; }
2. Declare and define the inner side of the class (implementation)
 class Student{ void set_age(int a){age = a;} int get_age(){return age;} }

In fact, this method is the same as the method of calling member functions in Java.

2.3 Access restrictions

Similar to java syntax, c++also provides three keywords:

  • public : This class and other classes can access
  • private : Only this class can access
  • protected : Only this class and derived classes can access.

However, the syntax format used is slightly different.

 class book { public: void setprice(double a); double getprice(); private: double price; };

With this format, you can set the attribute as public The variables or functions of are declared together. Duplicate write permission restriction symbols are avoided.

Of course, members with the same permissions can also be declared separately, and the order of declaration does not matter.

2.4 Accessing Member Variables/Functions

The created object is an instance of a class, so you can use it directly . Click the selector. This is the same as Java.

If the created pointer is an object, you need to use the -> Arrow selectors access members. There is no rule without pointers in Java.

 #include <iostream> using namespace std; class book { public: void setprice(double a); double getprice(); private: double price; }; void book::setprice(double a) { price = a; } double book::getprice() { return price; } int main() { book Alice; Alice.setprice(29.9); cout<<"The price of Alice is $"<<Alice.getprice()<<endl;    book *Harry = new book; Harry->setprice(49.9); cout<<"The price of Harry is $"<<Harry->getprice()<<endl; return 0; }

Note: the difference between C++class and struct

Both class and struct can define the structure of a class.

  • With the struct keyword, member variables or member functions defined in the structure are public by default.
  • With the class keyword, the member variables or member functions defined in the class are private by default,

There is no other difference.

3. Constructor

3.1 Definition of constructor

The declaration and definition methods of constructors are the same as those of ordinary functions. There are also two methods, but there are the following special points:

  • The function name of the constructor must be the same as the class name;
  • The constructor has no return value;
  • When we create class objects, the constructor will be automatically called, without our initiative to call.

These three points are the same as the syntax in Java.

Usually, when defining a class, When no constructor is defined, the system will automatically generate a default constructor. The default constructor is the constructor without any parameters. Other constructors with parameters are collectively referred to as constructors with parameters.

If any constructor is declared in the class, the system will not automatically generate a default constructor.

What constructor is used when creating an object? Just add a pair of parentheses after the object name, and the parenthesis parameters correspond to the corresponding constructor parameters:

 class book { public: book(){} book(char* a, double p); private: double price; char[] title; }; book::book(char[] a, double p) { title = a; price = p; } int main() { book Harry("Harry Potter", 49.9); return 0; }

3.2 Initialization parameter table

In addition to initializing member variables in the function body of the constructor, you can also Initialize parameters by following the constructor in the following format

 Constructor (parameter list): member variable 1 (initial value), member variable 2 (initial value)...... {}

for instance:

 class book { public: book(){} book(char *a, double p):title(a),price(p){} };

Yes, you are right. There is a function like way to assign values to member variables.

The essence of this writing method is to simplify the assignment of member variables. You can also define the constructor in a common way:

 book(char *a, double p){ title = a; price = p; }

In Java syntax, you can assign values to member variables in the initialization block, which is easy to understand.
But in C++, it provides such a The member variable name is used as the function name, and the parameter list is the value of the variable Initialize member variables in the form of.

It is worth noting that: The parameter initialization order is independent of the order in which the initialization table lists the quantities , parameter initialization order is only the same as The order in which member variables are declared in a class is related

3.3 Default values of constructor parameters

The function parameters in PHP can be assigned a default value before calling, because PHP does not support function overloading. In this way, when you call a function without assigning values to other parameters, other functions will also have a default value:

 function exampleFunction($parm1,$parm2 = "world"){ echo $parm1 ." ". $parm2; } exampleFunction("hello") //Output: hello world;

The above code clearly shows that the second parameter has been assigned a default value world When you do not give the second parameter, the second parameter still has a value.

The constructor of c++also supports the default assignment of parameters, such as:

 class book { public: book(){} book(char* a, double p = 5.0); private: double price; char * title; }; Book:: book (char * a, double p)//You can not specify default parameters when defining functions { title = a; price = p; }

At this point, when we create objects like this:

 Book Time("Time book")

The second constructor is called, and price Automatic assignment as default five

However, the constructor of the default parameter will conflict with some constructor overloads:

 book(char* a);

If we declare such a constructor again, compilation errors will occur when creating objects before, because the compiler does not know which constructor to call.

let me put it another way, Under the condition that C++supports overloading of constructors, it is basically unnecessary to use constructors with default parameters

*3.4 Transformation and Copy Constructor

3.4.1 Transformation constructor

The constructor can be divided into:

  • Constructor without parameters
  • Constructors with parameters (including constructors with default parameters)

among Constructor with parameters There are two special constructors in:

  • Transition constructor
  • copy constructor

Transformed constructors are no different from ordinary constructors The parameter list has only one parameter If this constructor is called when creating an object, it means that Convert parameters to objects of a class It's nothing special.

The special thing is that there is a Implicit type conversion: For example, if you create a string variable, but you pass the variable into a function whose parameter is a class object, it will automatically occur Implicit Object Type Conversion from String to Class Object

 class student { public: Student (char * n) {name=n;}//transformation constructor private : char * name; } void fun(Student studentObj){}; char * name = “Harry Potter”; fun(name);

At this time, the string name is automatically converted to an object of student class, and the transformation constructor is automatically called during the conversion.

but Implicit conversion It will bring debugging difficulties. You can add explict Keyword to avoid this automatic conversion.

let me put it another way, The transformation constructor is a kind of constructor with only one parameter, which can realize the function of converting parameters into class objects.

3.4.3 Copy constructor

4. Destructor

There is no need to design destructors in Java. Java has a system level garbage collection management program.

When creating an object, the system will automatically call the constructor When an object needs to be destroyed, the system will also automatically call the destructor.

Similar to the constructor, the destructor is also a member function, but it has the following special features:

  • No return value
  • No parameter, cannot be overloaded, so a class can only contain one destructor
  • The function name must be in the form of "~class name", and there can be a space between the symbol "~" and the class name

5. Advanced usage of classes

5.1 Constant pointer this

Similar to java, in In each member function of the class Contains a constant pointer, The pointer points to the object that called the function.

Similar to java, this pointer is only used to distinguish member variables and parameter names with the same name:

 void setprice(double price) { price = price; }

5.2 New and delete operators

There are two ways to create objects in C++. One is to directly use Class name Object name (constructor parameter list) The other way is to create new Keyword creation.

The two methods of creating objects have different space allocation methods.

  • The first kind of space is allocated in the stack and can be directly managed by the system. For example, outside the code block, the objects in the block will be cleaned up.
  • The second type of space is allocated on the heap. The size can be large, but the destruction is handled by the program itself.

use new Keyword will automatically call the constructor
use delete The keyword will automatically call the destructor

5.3 const keyword

Const indicates some data that people do not want to modify, which is similar to the final static There are similarities, but there are also many differences.

The const keyword can be defined on member variables, member functions, objects, and common references to objects.

5.3.1 Modifying (member) variables

This is easy to understand. Adding a keyword at the front of the variable indicates that secondary modification is prohibited after initialization. The initialization of const member variables can only be performed through the parameter initialization table

 const int a=5;

5.3.2 Modifying member functions

Const member function All member variables in the class can be used, but no member variable can be modified, and no non const member function in the class can be called

 Fun (formal parameter) const {}

5.3.3 Decorative objects

A class object decorated with const. Any member variable in the object cannot be modified.

therefore Cannot call any non const member function of this object , because calls to non const member functions will attempt to modify member variables.

 class A { public: void funcA() {} void funcB() const {} }; int main { const A a; a.funcB();    //  sure a.funcA();    //  error const A* b = new A(); b->funcB();    //  sure b->funcA();    //  error }

5.3.4 Reference of decorated objects

We use objects in some function parameters. At this time, we do not directly use objects as parameters, but use object references.

At this time, we add keywords before the object reference to avoid any modification of the object itself by the function:

 void display(const book &b) { b.setprice(59.9);  // compile error cout<<"The price of "<<b.gettitle()<<" is $"<<b.getprice()<<endl;  //ok }

5.3.5 Overloading Member Functions

Reference article: C++const keyword summary

5.4 Static keyword

Well, this keyword can be said to be consistent with Java.

5.4.1 Static Member Variables

This variable is synchronized with all objects of the class, that is, the variable of the class

5.4.2 Static Member Functions

5.5 Friend Functions and Friend Classes

5.5.1 Friend function

We know that objects cannot directly call private variables or private functions. Only functions in a class can use private variables or private functions of the class.

Friend function can Non member functions that directly access private members of a class It is a common function defined outside the class. It does not belong to any class, but It needs to be declared in the definition of the class , you only need to add the keyword friend before the name of the friend when declaring, and its format is as follows:

 friend   Return type function name (formal parameter);
  • The declaration of friend function can be placed in the private part of the class or in the public part. There is no difference between them, which means that they are a friend function of the class.
  • A function can be a friend function of multiple classes, and only needs to be declared separately in each class.
  • The method and principle of calling friend functions are consistent with those of general functions.

5.5.2 Friends

All member functions of a friend class are friend functions of another class , you can access hidden information in another class (including private members and protected members).

When you want a class to access the private members of another class, you can declare the class as a friend class of another class. The statement format for defining friend classes is as follows:

 Friend class name;

When you declare another class as a friend of the class, it indicates that All member functions of this friend class can use all information of this class This order is unidirectional.

Where: friend and class are keywords, and the class name must be a defined class in the program.

For example, the following statement indicates that class B is a friend class of class A:

 class A {  public: friend class B;  };

After the above description, all member functions of class B are friend functions of class A, which can access private and protected members of class A.

Note when using friend classes

  • Friendship cannot be inherited.
  • The friendship relationship is one-way and not exchangeable. If class B is a friend of class A, class A is not necessarily a friend of class B. It depends on whether there is a corresponding declaration in the class.
  • Friendship is not transitive. If class B is a friend of class A, and class C is a friend of class B, class C is not necessarily a friend of class A. It also depends on whether there is a corresponding declaration in the class

Reference article:

C++Friend Functions and Friend Classes

Last modification: February 24, 2019
Do you like my article?
Don't forget to praise or appreciate, let me know that you accompany me on the way of creation.