Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the primer class in C++

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use the primer class in C++, the article is very detailed, has a certain reference value, interested friends must read it!

The basic idea of class is data abstraction and encapsulation.

Data abstraction is a programming technology that depends on the separation of interface and implementation.

1. Define Abstract data types 1.1 Design Sales_data classes

The declaration of the member function must be inside the class, and the definition can be internal or external

Non-member functions that are interfaces, such as print and read, declare that the definition is outside the class.

The functions defined within the class are implicit inline functions

The this pointer is implicitly initialized when a member function is called

Any custom parameter or variable named this is illegal

Const member function

Const member function: a function that adds the const keyword to the argument list

The function of const is to change the type of implicit this pointer

By default, the type of this is a constant pointer to a non-constant of the type. Therefore, you cannot bind this to a non-constant object (you cannot bind this to other objects), and therefore you cannot call normal member functions on constant objects (you cannot access ordinary member functions with const objects).

Const member functions improve the flexibility of functions

Constant objects, and references or pointers to constant objects, can only call constant member functions.

The compiler processes classes in two steps.

1. Compile the member declaration.

two。 After all member declarations have been compiled, compile the member function body. Therefore, after the member declaration appears in the body of the member function, the compiler can compile normally.

Define the function body outside the class

You need to add the class name before the function name::, and the remaining code after the class name is within scope

If the return type is also declared within the class, you need to add the class name:: before both the function name and the return type.

If it is declared as a const member function within a class, the const keyword cannot be omitted when defined externally.

If you need to return the class itself, use return * this

1.2 define class-related non-member functions

Class-related non-member functions: belong to the interface of the class, but not to the class itself.

Function declarations and definitions are usually separated. In the same header file as the class declaration.

Usually, copying a class is actually copying its members. (if you want to copy and perform other operations, check the copy assignment function)

Sale_data s 1. 3 member 1. 3 constructors of S1 have been copied by S1. 2

The task of the constructor is to initialize the data members of the class object

As long as the class object is created, the constructor must be executed

The constructor name is the same as the class name, and there is no return type, and the rest is the same as the normal function.

Constructor cannot be declared as const

Default constructor

If a class contains built-in or composite type members, it is appropriate for the class to use the composite default constructor only if all of these values are assigned to the initial values within the class.

If class a contains a member class b, if b does not have a default constructor, the compiler cannot construct the correct default constructor for a.

If other constructors are defined, the compiler does not construct the default initial function

If there is an initial value in the class, use it to initialize the member

Otherwise, members are initialized by default

The default constructor does not require any arguments

If no constructor is explicitly defined for the class, the compiler implicitly constructs a synthetic default constructor.

The default constructor for the composite initializes class members according to the following rules

Some classes cannot rely on the default constructor of the composite

Class A {/ / defines a constructor whose argument is string / / at this time, the compiler will not synthesize the default constructor A (std::string a) {}} A _ a _ A _

Adding = defualt after the argument list requires the compiler to generate a default constructor

= defualt can appear within the class with the declaration or outside the class as a definition.

If inside the class, the default constructor is inline, and if outside the class, it is not inline by default.

Class A {A () = defualt;} An a handle / correct, the compiler generates a default constructor

List of initial values of constructor

There is a compiler that does not support in-class initial values, so the default constructor does not apply (because the default constructor initializes class members with in-class initialization values), you should use the constructor initial value list.

The function initial value list is the argument list as follows (colons and code between colons and curly braces:: bookNo (s))

The constructor should not easily override the initial value in the class unless the newly assigned value is different from the original value

During the constructor, members that do not appear in the function initialization list are initialized by default

Class Sales_data {Sales_data (const std::string & s unsigned nmaging double p): bookNo (s), units_sold (n), revenue (pairn) {} / / when the compiler does not support in-class initial values, Sales_data (const std::string & s) can be defined as follows: bookNo (s), units_sold (0), revenue (0) {}}

To define a constructor outside a class, to declare which class constructor it is, add the class name before the function name:

Sales_data::Sales_data (std::istream cin) {read (cin,*this);} 1.4 copy, assignment and deconstruction

The compiler synthesizes copy, assignment, and destroy operations for the class.

The version generated by the compiler copies, assigns, and destroys each member of the object

2 access control and encapsulation

Access specifier

Members after the public specifier can be accessed throughout the program

The member after the private specifier can be accessed by the member function of the class

A class can contain 0 or more access specifiers, valid until the next specifier appears.

The only difference between the class and struct keyword definition classes is that

The default area of class before the first access specifier appears is private

The default area of struct before the first access specifier appears is public

2.1 Friends

Class can allow other classes or functions to access its non-public members. The way to do this is to declare friends with the keyword friend.

The declaration of friends can only be within the class.

There is no limit to the location of the friend declaration, and it is best to declare the friend centrally before the class definition begins or ends.

Benefits of encapsulation

Ensure that the user code does not inadvertently break the state of the encapsulated object

The implementation details of the encapsulated class can be changed at any time.

The declaration of the friend in the class only specifies the access permission, not a function declaration in the usual sense.

If you want the user of the class to be able to call a friend function, you need to declare the function in addition to the friend declaration.

To make the friend visible to the class user, the friend declaration is prevented from being in the same header file as the class itself

Some compilers force that friend functions must be declared outside the class before being used

2.2 other features of the class

Next: type members, in-class initial values of class members, variable data members, inline member functions, return * this from member functions, how to define the use of class types, friend classes

2.2.1 re-exploration of Class members

Category name (type member):

The type name defined in the class has access restrictions like other members, which can be public or private

Category names must be defined before they are used

(recall: class member variables can be defined after class member functions, but are used in class functions because the compiler compiles class member variables first, followed by first class member functions.)

Type members usually appear at the beginning of the class

Class Screen {public: / / is equivalent to using pos = std::string::size_type typedef std::string::size_type pos;}

Make a member as an inline function

The function defined inside the class is automatically inline, and the function defined outside the class. If you need to declare the inline function, the inline;inline member function should also be defined in the same folder as the corresponding class.

Inline Screen& Screen::move (pos r pos c) {pos row = ringing widths; cursor = row + c; return * this;}

A mutable data member that will never be a const, even if it is a member of the const object

Class Screen {public void some_member () const;private: mutable size_t access_ctr;// uses mutable to declare a variable data member} void Screen::some_member () const {+ + access_ctr;// can still modify a variable data member} even in the const member function

The initial value in the class uses the initialization form of = or the direct initialization form enclosed in curly braces.

2.2.2 return the member function of * this

Note whether the return type is a reference. Whether it is a reference or not has a great influence on the use of the function.

Inline Screen & Screen::set (char ch) {content [cursor] = ch; return * this;} inline Screen & Screen:: move (pos r * width + col; return * this;} Screen s) / / the move function returns s itself, so you can then call the set function / / and the move function returns a reference to Screen. If it does not return a reference, it will return a new Screen object s.move (3prime2) .set ('!')

The constant reference is returned from the const function, and the class member variable cannot be modified in the const function

Overloading using the const function

Write the function display to print the contents in Screen, which should be a const function because it is just a presentation and does not need to modify the value.

But I want to be able to move the cursor after the display: s.display (). Move (2p3). This requires that the value returned by display is modifiable, so this should not be a const function.

Based on const overloading, it can be overloaded depending on whether the Screen object is const.

It is recommended to use more functions such as do_display to complete the actual work, so that public code uses private functions.

Can be modified centrally

No extra overhead.

Class Screen {public: Screen* display (std::ostream & os) {do_display (os); return * this;} const Screen* display (std::ostream & os) const {do_display (os); return * this } private: void do_display (std::ostream & os) const {osheight; double para_height = height; double global_height =:: height;} 2.5.1

Constructor initial value list when the class has reference members and const members, it must be initialized with the initial value list in the constructor

It is recommended to form the habit of using the initial value of the constructor.

The initial value list only describes the values of the initial value members and does not limit the specific execution order of the initial values; the order of the initial values is consistent with the order in which they appear in the class definition (when some compilers do not match the order in the initial value list and the class, a warning message is generated)

/ / example dangerous operation strcut X {/ / actually initializes according to the declared order. When initializing rem first, the value of base is unknown X (int I int j): base (I), rem (base%j) {} int rem,base;}

It is recommended that you use the initial values list in the same order as the variables in the class, and if possible, avoid initializing other members with some members.

2.5.2 delegated constructor

The only entry to the member initial value list is the class name. You can use the constructor to call other constructors, and the calling process should be written in the initial value list.

Class Sale_data {public: Sales_data (const std::string & s Magneto unsigned slotnummagagem double price): units_sold (s_num), revenue (s_num*price), BookNo (s) {} Sales_data (): Sales_data (", 0Cool 0) {} / / delegate to the previous constructor} 2.5.3 function of default constructor

The default construction parameters are executed when the object is initialized by default or by value

The default initialization occurs in:

1. When a non-static variable or array defined without any initial values within the scope of the block

two。 The class itself contains members of the class type and uses the default constructor of the composite

3. When a class type member is not explicitly initialized in the constructor initial value list

Value initialization occurs when:

1. When initializing an array, the number of initial values provided is less than the size of the array

two。 When defining a local variable without using the initial value

3. When writing an expression like T () to explicitly request value initialization, where T is the type name. For example, vector accepts an argument indicating the size of the vector

If other constructors are defined, the compiler is no longer generating the default constructor, so it is best to require us programmers to provide a constructor

2.5.4 implicit class type conversion

Conversion constructor: you can define a rule for converting a constructor type from a constructor parameter to a class type through a constructor called by an argument.

Vector str_vec;// requires a string for push, but a string for passing parameters. The transformation constructor str_vec.push_back ("Xiaohei ~") of string is used here.

The transformation constructor allows only one step to construct the transformation.

A constructor that requires multiple arguments cannot perform an implicit conversion

/ / Sales_data has a constructor with the parameter string / / the combine of Sales_data is the method: / / Sales_data& Sales_data::combine (const Sales_data&); Sales_data item;item.combine ("infinite ~") / / error, only one-step construction of item.combine (string ("infinite ~")) / / correct, and only one-step implicit construction conversion from string to Sales_data

Using explicit to suppress implicit conversions defined by constructors

Class Sales_data {explicit Sales_data (const string&): bookNo (s) {};. / / other declarations} item.combine (string ("infinite ~")); / / error, explicit blocked implicit conversion

The explicit function can only be used for direct initialization

/ / the constructor of Sales_data: explicit Sales_data (const string&): bookNo (s) {}; string bookNo = "001"; Sales_data item1 (bookNo); / / correct, direct initialization Sales_data item2 = bookNo;// error, copy initialization

Although the compiler does not use the constructor of explicit for the implicit conversion process, you can use explicit cast

String bookNo = "001"; item.combine (bookNo); / / error, explicit prevents implicit conversion of item.combine (static_cast (bookNo)); / / correct, cast 2.5.5 aggregates

The definition of the aggregate class. A class that satisfies the following conditions is called an aggregate class.

1. All members are public.

two。 No constructor is defined

3. No in-class initial value

4. No base class, no virtual function.

The aggregate class can be initialized using the list of initial values of members enclosed by {}

Class Data {public: int ival; string s;} / / order must be the same Data val1= {0, "Confucius"}; 2.5.6 literal constant

The arguments and return values of the constexpr function must be of literal type

Literal types include arithmetic types, pointers, references, data members that are aggregate classes of literal types and classes that meet the following conditions.

1. Data members are literal types

two。 Class must contain a constexpr constructor

3. Use the destructor defined by default

4. If a data member contains an in-class initial value, the initial value must be a constant expression; if the data member belongs to a certain type, the initial value must use its own constexpr constructor

The constructor cannot be const, but it can be constexpr.

Literal constant class that provides at least one constexpr constructor

Constexpr constructor

Is a constructor with no return statement

Is the constexpr function, and the only executable statement is the return statement

Therefore, the body of the constexpr constructor function is empty, and construction initialization can only be performed by initializing list values.

Class Data {public: constexpr Data (int para_i,string para_s): ival (para_i), s (para_s) {} int ival; string s;} constexpr Data data (1, "eat barbecue"); static member of class 1.6

Use static to declare a static member in a class that is associated with the class rather than with the class object

Static member functions are also not bound to any class objects, and static member functions do not contain this pointers. (including explicit calls to this and implicit calls to non-static members)

When defining the static function externally, you cannot repeat the declaration statement inside the class where the static,static keyword appears.

Static members cannot be initialized within a class. Each static member must be defined and initialized outside the class, so once defined, it exists throughout the life cycle of the program.

The best way to ensure that objects are defined only once is to put the definitions of static data members in the same file as those of other non-inline functions

In-class initialization of static members

In general, static members of a class should not be initialized inside the class

Static members must be of literal constant type (constexpr)

Even if a constant static data member is initialized inside the class, it should usually be defined outside the class (so that the life cycle lasts until the end of the program).

Special usage scenarios for static members

The type of a static data member can be the type to which it belongs

Class Bar {public://...provite: static Bar mem1;// is correct, static member can be incomplete type Bar* mem2;// is correct, pointer member can be incomplete type Bar mem3;// error}-static member can be used as default argument class Screen {public: Screen& clear (char = bkground) private: static const char bkground } these are all the contents of this article entitled "how to use primer classes in C++". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 204

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report