C + + Primer Learning Notes _15_ class and Data Abstraction (1) _ Class definition and declaration

Source: Internet
Author: User
Tags class definition



C + + Primer Learning Notes _15_ class and Data Abstraction (1) _ Class definition and declaration



In C + +, classes are used to define their own abstract data types. By defining types to correspond to the various concepts in the problem to be solved, we can make it easier to write, debug, and modify programs. You can make your own defined data types as easy and intuitive as the built-in 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: Recap



Simply put, 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 using all code of that type: members defined in the private section can be accessed by other class members.



All members must be declared inside the class, and once the class definition is complete, there is no way to add members.





2. Constructor function



When you create a class object, the compiler automatically uses a constructor to initialize the object, which means that the constructor is used to set the appropriate initial value for each data member.



Constructors typically use a constructor to initialize the list to initialize the data members of the object. The constructor initialization class table consists of the member name and the initial value with parentheses , followed by the formal parameter list of the constructor, and begins with a colon (:).



For example: Sales_item (): Units_sold (0), Revenue (0) {}





3. member functions



A function defined inside a class defaults to an inline function (inline).



Functions defined outside the class must indicate that they are in the scope of the class.



After the Const keyword is added to the formal parameter list, the member function can be declared as a constant, such as Double avg_price () const;



The const must appear in both the Declaration and the definition, and if it appears only in one place, a compile-time error will occur!





// within the class
double avg_price () const;
// out of class
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 interfaces and implements separation : The designer of a class must be concerned about how the class is implemented, but programmers who use the class do not need to know these details .



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



1. Access designator implementation abstraction and encapsulation



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



2) The code that uses the class does not have access to members with private labels. Private encapsulates the implementation details of the type.





"The difference between class and struct"



Class default is private, struct default is public!





2. Different categories of programming roles



The designer of a good class defines an intuitive and easy-to-use class interface, and users (who can refer to programmers here) simply care about the part of the implementation that affects their use in the class.



Note that C + + programmers often refer to the user of the application and the consumer of the class as "user".





"Key concepts: the benefits of data abstraction and encapsulation"



1) Avoid unintentional user-level errors within the class that may destroy the state of the object.



2) Over time, you can refine your class implementation based on demand changes or bug reports without changing user-level code.



Annotations



Changing the class definition in the header file effectively alters the program text for each source file that contains the header file , so code that uses the class must be recompiled when the class changes.





Iii. more on class definitions



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 type aliases to simplify classes



In addition to defining data and function members, a class can also define its own local type name. If you provide a type alias for Std::string::size_type, then the screen class will be a better abstraction (place the index definition in the public section):





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 overload other member functions of this class.



Overloaded member functions and normal functions apply the same rules: the number of parameters and the type of two overloaded members cannot be identical. The function matching procedure used to invoke a non-member overload function is also applied to the call of the overloaded member function.






4. Defining overloaded functions





class Screen
{
public:
    typedef std :: string :: size_type index;
    // Overloaded 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 an inline function



A member function defined inside a class, which is the inline function by default. However, you can also explicitly specify the member function as inline:





class Screen
{
public:
    typedef std :: string :: size_type index;
 
    // The functions in the class are inline functions by default
    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;
};
 
// Declared as inline in the class body, there is no need to declare it again
char Screen :: get (index r, index c) const
{
    index row = r * width;
    return contents [row + c];
}
 
// Even if it is not declared in the class body, it can be added outside
inline Screen :: indexScreen :: get_cursor () const
{
    return cursor;
}





It is legal to specify inline at the declaration and definition. One of the benefits of defining inline outside the class is that it makes the class easier to read.





Annotations



Like other inline, the definition of an inline member function must be visible in every source file that invokes the function. not defined within the class definition inline member functions , the definition should typically be placed in the same header file as the class definition .





Iv. class declarations and class definitions



In a given source file, a class can only be defined once. If you define a class in more than one file, the definitions in each file must be exactly the same .



You can declare a class without defining it:





Forward Declaration class screen;





Before and after a declaration, class screen is an incomplete type, that is, the screen is known to be a type, but does not know which members are included.



An incomplete type (Incompletetype) can only be used in a limited way . An object of this type cannot be defined . A non-full type can only be used to define pointers and references to that type , or to declare (rather than define) a function that uses that type as a formal parameter type or return type .



The class must be fully defined before the object of the class is created. The class must be defined rather than declared , so that the compiler will reserve the appropriate storage space for the object of the class. Similarly, a class must already be defined before using a reference or pointer to access the members of the class .





1. Use class declarations for members of the class:



A data member can be specified as a class type only if the class definition has already been previously present. If the type is not fully typed , then the data member can only be a pointer or reference to the class type .



A class cannot have a data member of its own type , because it can only be defined when the class definition body is complete. However, this class can be considered declared as long as the class name is present. Therefore, a data member of a class can be a pointer or reference to its own type :



Class Linkscreen



{



Screen Window;



Linkscreen *next;



Linkscreen *prev;



};





V. Classes of objects



When you define a class, you define a type. Once a class is defined, you can define an object of that type. when you define an object, it allocates memory space for it, but ( generally ) No storage allocations are made when defining types . Once an object is defined, the compiler assigns it enough storage space to hold a class object



Each object has its own copy of the class data member. Modifying one of these objects does not alter the data members of other objects of that class.





1. Defining objects of class type



Once you have defined a class type, you can use it in the following two ways.



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



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





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





2. Why the definition of a class ends with a semicolon



Since the class definition can be followed by an object definition list, the definition must end with a semicolon, which can give a "practice: Master Element"





// vs2012 test code
#include <iostream>
#include <vector>
 
usingnamespace std;
 
#definen 5
 
// Method 1: Every time you find two different elements, delete them in pairs, that is count--, and 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 find the 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);
} 





Operation Result:



Input: 23 2 3 2



2





Annotations



In general, it's a bad idea to define an object as part of a class definition !!! Doing so will make the operation difficult to understand. For the reader, it can be confusing to combine two different entities (classes and variables) in a single statement.





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



C + + Primer Learning Notes _15_ class and Data Abstraction (1) _ Class definition and declaration


Related Article

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.