C ++ Primer learning note _ 15 _ class and data abstraction (1) _ class definition and declaration, primer_15

Source: Internet
Author: User

C ++ Primer learning note _ 15 _ class and data abstraction (1) _ class definition and declaration, primer_15

C ++ Primer learning note _ 15 _ class and data abstraction (1) _ class definition and Declaration

In C ++, classes are used to define their own abstract data types. Defining types to correspond to various concepts in the problem to be solved makes it easier for us to write, debug, and modify programs. This makes it as easy and intuitive as the built-in data types.

Take a look at the Sales_item class:

class Sales_item{private:    std::string isbn;    unsigned units_sold;    double revenue; public:    double ave_price() const;    bool same_isbn(constSales_item &rhs) const    {        return isbn ==rhs.isbn;    }    Sales_item():units_sold(0),revenue(0) {}}; double Sales_item::ave_price() const{    if (!units_sold)    {        return 0;    }    return revenue /units_sold;}

I. Class Definition: repeat briefly

To put it simply, a class defines a new type and a new scope.

 

1. Class Members

A class can contain several public, private, and protected parts. We have used public and private access labels: Members defined in the public section can be accessed by all code using this type: Members defined in the private section can be accessed by other class members.

All members must be declared within the class. Once the class definition is complete, there is no way to add members.

 

2. Constructor

When creating a class object, the compiler automatically uses a constructor to initialize the object. That is, the constructor is used to set an appropriate initial value for each data member.

A constructor uses a constructor to initialize data members of an object. A constructor initialization table consists of a member name and an initial value with parentheses. It follows the constructor's parameter table and starts with a colon.

For example: Sales_item (): units_sold (0), revenue (0 ){}

 

3. member functions

The function defined in the class is inline by default ).

The Functions Defined externally in the class must indicate that they are in the scope of the class.

After the const keyword is added to the form parameter table, you can declare the member function as a constant, for example, double avg_price () const;

Const must appear in the declaration and definition at the same time. If it appears only in one place, a compilation error will occur!

// Double avg_price () const; // double Sales_item: ave_price () // error {if (! Units_sold) {return 0;} return revenue/units_sold ;}

Ii. Data abstraction and Encapsulation

Data abstraction is a programming technique that relies on the separation of interfaces and implementations:Class designers must be concerned about how classes are implemented, but programmers who use this class do not have to understand these details..

Encapsulation is a technology that combines low-level elements to form new and high-level entities!

1. Access label implementation abstraction and Encapsulation

1) all parts of the program can access members with the public label. The abstract view of data type is defined by its public member.

2) code using classes cannot access members with private labels. Private encapsulates the implementation details of the type.

 

[Difference between class and struct]

The default class is private, and the default struct is public!

 

2. Different types of programming roles

Designers of good Classes define intuitive and easy-to-use class interfaces, while users (which can be programmers here) only need to care about the part of implementations that affect their use in the class.

Note that C ++ programmers often refer to application users and class users as "users ".

 

[Key Concept: benefits of data abstraction and encapsulation]

1) avoid unintentional user-level errors within the class that may damage the object state.

2) over time, class implementation can be improved based on demand changes or defect reports without changing user-level code.

[Note]

Changing the class definition in the header file can effectively change the program text of each source file that contains the header file. Therefore, when the class changes,Code using this class must be re-compiled.

 

Iii. More about class definition

1. Multiple Data members of the same type

General statement:

class Screen{public:    //... private:    std::string contents;    std::string::size_type cursor;    std::string::size_typeheight,width;};


2. Use the type alias to simplify the class

In addition to defining data and function members, the class can also define its own local type name. If std: string: size_type provides a type alias, the Screen class will be a better abstraction (put the index definition in the public part ):

class Screen{public:   //...   typedef std::string::size_type index; private:   std::string contents;   index cursor;   index height,width;};


3. member functions can be overloaded.

Member functions can only reload other member functions of this class.

The number and type of parameters of two overloaded members cannot be the same. The function matching process used to call a non-member overload function is also applied to the call of the overload member function.


4. Define overload Functions

Class Screen {public: typedef std: string: size_type index; // overload function get char get () const {return contents [cursor];} char get (index ht, index wd) const; private: std: string contents; index cursor; index height, width ;};

5. explicitly specify the inline function

The member function defined in the class is the inline function by default. However, you can explicitly specify the member function as inline:

Class Screen {public: typedef std: string: size_type index; // The default function in the class is the inline function char get () const {return contents [cursor];} inline char get (index ht, index wd) const; index get_cursor () const; private: std: string contents; index cursor; index height, width ;}; // if it has been declared as inline in the class body, it is unnecessary to declare char Screen: get (index r, index c) const {index row = r * width again; return contents [row + c];} // you can add inline Screen: indexScreen: get_cursor () const {return cursor;} on the outside even if it is not declared in the class body ;}

It is valid to specify the inline in the declaration and definition. One advantage of defining inline externally in a class is that it makes the class easier to read.

 

[Note]

Like other inline functions, the definition of inline member functions must be visible in each source file that calls the function. Inline member functions not defined in the class definition body should be defined in the same header file with the class definition.

 

Iv. Class declaration and Class Definition

In a given source file, a class can only be defined once.If you define a class in multiple files, the definitions in each file must be identical..

You can declare a class without defining it:

// Declare class Screen in the forward direction;

After declaration and definition, class Screen is an incomplete type, that is, it is known that Screen is a type, but does not know which members are included.

The incomplete type (incompletetype) can only be used in a limited manner.Objects of this type cannot be defined.. Incomplete types can only be used to define pointers and references to this type, or to declare (rather than define) functions that use this type as the parameter type or return type.

Before creating a class object, you must define the class completely. It must be a definition class rather than a declaration class. In this way, the compiler will reserve a storage space for the class objects. Similarly,Before using a referenced or pointer to a member of the category class, you must have defined the class.

 

1. Use the class declaration for the class members:

Only when the class definition has already appeared before can the data member be specified as the class type. If the type is incomplete, the data member can only be a pointer or reference to the type of this class.

Because the class can be defined only after the class definition body is complete,Therefore, a class cannot have its own data members.. However, as long as a class name appears, it can be consideredThis class has been declared. Therefore, the data member of a class can be a pointer or reference to its own type:

Class LinkScreen

{

Screen Window;

LinkScreen * next;

LinkScreen * prev;

};

 

V. class objects

A class is defined. Once a class is defined, objects of this type can be defined. When defining an object, it will be allocated memory space, but (generally speaking) It will not be stored for allocation when defining the type. Once an object is defined, the compiler allocates enough storage space for a class object.

Each object has a copy of its own class data member. Modifying one of the objects does not change the data members of other objects.

 

1. Define objects of the class type

After defining a class type, you can use it in either of the following ways.

1) Use the class name directly as the type name.

2) Specify the class or struct keyword, followed by the class name:

Screen scr; // the two statements work the same class Screen scr;

2. Why does the class definition end with a semicolon?

The definition can be followed by an object definition list after the class definition. Therefore, the definition must end with a semicolon. You can give "Practice: principal element"

// Vs2012 test code # include <iostream> # include <vector> usingnamespace std; # definen 5 // Method 1: Delete each element in pairs, that is, count --, the rest must be what you want. Time Complexity: O (n) classSolution {public: int majorityElement (vector <int> & num) {int element; int length = num. size (); int count = 0; for (int I = 0; I <length; I ++) {if (count = 0) {element = num [I]; count = 1 ;}else {if (num [I] = element) count ++; else count -- ;}} count = 0; for (int I = 0; I <length; I ++) {if (num [I] = element) count ++;} if (count> length/2) cout <element <endl; else cout <"can not findthe majority element" <endl; return 0 ;}} lin, lin2; int main () {int a; vector <int> num; for (int I = 0; I <n; I ++) {cin> a; num. push_back (a);} lin. majorityElement (num );}

Running result:

Input: 23 2 3 2

2

 

[Note]

Generally, defining an object as part of a class definition is a bad idea !!! This will make the operations hard to understand. It is confusing for readers to combine two different entities (classes and variables) in one statement.

 

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.