C ++ Primer: Chapter 7 summary


Chapter 7 class

7.1 defining abstract data types

The basic idea of the class: data abstraction, encapsulation.
Data abstraction: that relies on the separation of interfaces and implementations programming and design techniques. A user interface comprising operations that can be performed; for data class members include, responsible for various functions required for the private body and the definition of the function of the class interface.
Interface and implementation separation package implementation class. Class packaged hide implementation details, the user can use the interface to achieve some can not be accessed.

  1. User class is end-user programmers, rather than the application.
  2. Class designers to consider implementation class, the class is easy to use; the user interface class class use only, regardless of the implementation mechanism of the class.

Introduction of member functions

  1. Member function can only be declared within the class, the class or classes may be defined outside; non-member function declarations and only outside the class definition.
  2. Member function defined within the class inline function is implicit.

Introduction of this

  1. this is an implicit parameter itself is constant pointer , which points to the object the function was called.
  2. this parameter is defined implicitly, any custom parameters or variables named this is illegal.
//this的类型:Sales_data * const
total.isbn(); // this=&total;

The introduction of const member functions

  1. In the const member functions, this is a per se to which it refers and the pointer is constant .
  2. Constant object, and the object of constant references and pointers can only call const member functions ; ordinary object can call ordinary member functions and const member functions.
  3. For const member functions , which point to this constant, constant objects can be invoked and const object, function, flexibility and better; for ordinary member functions , which this very point amount, the amount can only be called very subject.
// f:成员函数
// 第1个const:返回值是常量
// 第2个const:形参是常量
// 第3个const:函数是常量成员函数
const int A::f(const int ci) const 
{
    return ci;
}

Define a function to return this object

A& A::f(A& a)
{
    .....
    return *this; // 返回调用该函数的对象
}
a1.f(a2); // 返回对a1的引用

The definition of the relevant class of non-member functions

  1. Function declarations and definitions stored separately. Non-members of the same general function declarations in the header file and class declaration.
  2. Belonging to the same class and array IO not copy type, it can be passed by reference.
  3. Output function performs tasks should be reduced to control the format, such as line breaks generally added by the user.

Constructor

  1. Constructor class name and the name of the same, non-return type, can not be declared as const, to initialize a class object data members.
  2. Default constructor (without any arguments); Synthesis default constructor (the constructor created by the compiler).
  3. Synthesis default constructor is only suitable for very simple class, Common class must define a default constructor. Because only when any class constructor function is not declared, the compiler will default constructor is synthesized; built-in or compound type (array, pointer) data members is undefined default initialization; include other members of the class of class type and class type has no default constructor, the compiler can not be synthesized default constructor.
  4. Constructor initializer list.

Copy class assignment and destructor

  1. The compiler can be synthesized copy, assignment and destruction operations. But other than the allocation resource class requires the object class (e.g., dynamic memory management), often synthesized version of failure.
  2. Use vector or string can avoid the complexity of the allocation and release of memory.

7.2 Access Control package

Access specifiers: public, private

  1. used to define the public interface for the classes and member functions of the object visible; private for enclosing implements the interface for the member function is visible.
  2. struct default access is public, class default access permissions are private. If all class members are public, using struct; if there are private classes, use class.

Friend: Let the other class or function to access non-public members of the class itself

  1. Friend declarations can only appear in a class that specifies access only, instead of a normal function declaration, it is a function declaration can not be omitted.
  2. The best start in the class definition or declaration centralized position before the end of the friend.

Other features like 7.3

Class members: a member type, inline member functions, overloaded member function, the variable data members (the mutable), class data members initialized

  1. The definition and use of ordinary members can not order, but members must first define the type of re-use. Type members are usually found in the type of place to start, and usually use typedef using.
  2. If any of the constructor in the class declaration, the compiler will not default constructor is synthesized, if desired default constructor must be explicitly declared.
  3. Member function implicitly inline explicit inline type outer joint.
  4. Common separation function declarations and definitions, the function declaration in the header file, define the function of the same name in the source file. Exception: inline functions, constexpr functions and classes defined in the header file.
  5. For variable data members const object, const member functions are modifiable.
  6. The initial value of the class to be represented by an equal sign or braces.

Return * this member function.

  1. For the return * this function, if the return type is not referenced, the function returns a copy of the object; if the return type is a reference, returns the object itself.
  2. const member functions return * this as a reference, then its return type is a constant reference.
  3. Depending on whether the parameter is a const, const member functions determined whether the overloaded functions.
class A
{
    A &f1(int x) // 返回*this
    {
        return *this;
    }
    A &f2(const int x) // 形参是const
    {
        return *this;
    }
    A &f3(int x) const; // 成员函数是const
    {
        return *this;
    }
};

Class Type

  1. Members of the class type and class of the list has nothing to do. For both classes, even if the same list of members, they are also different types.
  2. Forward declarations: only temporarily does not define the class declaration class, then class is an incomplete type. Only incomplete type is used to define the type of reference point, or pointer, an incomplete type declaration parameters or function return values.
  3. Only after completion of all classes considered class is defined, so when the data members of the class declaration, the class is not fully specified, only refer to the class declaration point or pointer type, the type can not be declared. To create a class of objects or members access to the class after the class definition.

Friend Revisited

  1. Class member functions and classes themselves can be used as a friend.
  2. A designated class friend class, the Friends of the meta-class member functions can be accessed by all members of this class.
  3. Friendship is not transitive. Each class is only responsible to control their friend class and friend functions.
  4. If overloaded function as a friend, the need for overloaded functions in each function as a friend declaration.
  5. Friend declaration only affects access, not a real statement. Before the class declaration and use of friend functions, best first real statement.

7.4 class scope

  1. A class is a scope. Outside the scope of, the object, and pointers reference member selection operator - data members and member functions of the class accessed by the scope operator ((and>.): Access :) class type member.
  2. Scope parameter list and the function body after the class name in the class.
  3. Name Lookup (process of finding the best match with the statement names) typically from the inside out , first find the code names used in the previous block, then look in the enclosing scope.
  4. When you define a class, the compiler will first compile member declarations until all visible after the class compiled function body.
  5. Not redefine represent a type of the domain name in the enclosing class.
  6. Not recommended for use as a parameter the name of a member of the member function in the class.
  7. If the name lookup function in the body of a member function, the first function in the body and in the name of the former use code lookup, then look in the class, and finally former member function definition domain lookup function.

7.5 constructor Revisited

Constructor initialization list

  1. Constructors recommended initial value. The difference between the initialization and assignment is related to the underlying efficiency of the former direct initialize data members, which is initialized by assignment. In particular, when the members are const, reference, or belonging to a certain class type is not provided a default constructor, initial values must be provided by the constructor initialization list .
  2. Constructor initialization list only shows values ​​for initializing members whose initialization sequence is executed in the order defined by the members. Consistent with members of the order to make the best constructor declared initial value, to avoid the use of certain members of the other members initialized.
  3. If the constructor arguments for all provide a default argument constructor is the default constructor.

Commissioned constructor

  1. Other commissioned constructor uses it belongs to the class constructor performs its own initialization process, or entrust it to own some (or all) responsibility to other constructors.
#include <iostream>
#include <string>
using namespace std;

std::istream &read(std::istream &is, Sales_data &item);

class Sales_data
{
public:
    Sales_data(string s, unsigned cnt, double rev) : bookNo(s), units_sold(cnt), revenue(cnt * rev) {}

    Sales_data() : Sales_data("", 0, 0) {}
    Sales_data(string s) : Sales_data(s, 0, 0) {}
    Sales_data(std::istream &is) : Sales_data()
    {
        read(is, *this);
    }

private:
    string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;

    friend std::istream &read(std::istream &is, Sales_data &item);
};

std::istream &read(std::istream &is, Sales_data &item)
{
    int price;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = item.units_sold * price;
    return is;
}

int main()

    return 0;
}

The default constructor role

  1. When the object is a default value is initialized or the initialization is performed automatically default constructor.
  2. Default initialization situation occurs: the initial value without any scope is defined in a block of non-static variable or array; class itself contains a member of a class type and synthetic default constructor; initial members of a class type is not in the list of values ​​constructor explicitly initialized.
  3. Initializes the value of the occurrence of: providing an initial value when the number of array initialization is less than the array size; initial value is not used to define a local static variables; writing expressions of the form T () explicitly requested value is initialized.
  4. If define other constructors, it is preferable to provide a default constructor.
  5. A A (); is a function declaration, A a; A a class object is created.

Class implicit type conversion.

  1. Conversion Constructor: If the constructor function accepts an argument , it can be converted to such parameters implicitly type.
  2. The compiler allows only perform one step of the class type conversion.
  3. explicit suppressed implicit conversion constructor defined. explicit only a constructor argument is valid, the constructor arguments not containing a plurality of implicit conversion; just use the explicit statement at class constructor, not repeated as defined outside the class; explicit constructor can be used direct initialization, rather than copy initialization; may be displayed on the explicit constructor cast.
  4. Accepts a single parameter const char * string constructor function is not explicit; and accepts a capacity parameter vector constructor is explicit.
  5. An implicit type conversion type which temporary variables can not be modified, can be regarded as constant, is transmitted only to the constant reference, and is not transmitted to non-const reference (the value of the temporary variable is a right side, left-const reference value is initialized using only).
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    //非explicit构造函数
    const char c = 'a';
    const char *p = &c;
    string s1(p);
    string s2 = (p);
    //explicit构造函数
    // vector<int> v1 = (10);
    vector<int> v1(10);//explicit构造函数只能直接初始化

    return 0;
}

Class polymerization

  1. Aggregate class satisfies the condition: all members are public; not define any constructor; not within the class initializer; no base classes and virtual functions.
  2. The initial member list of available aggregate class value enclosed in curly braces initialization.
    Example:
#include <iostream>
using namespace std;
struct Sales_data
{
    string bookNo;
    unsigned units_sold; //聚合类无类内初始值
    double revenue;
};

int main()
{
    Sales_data item = {"978-0590353403", 25, 15.99};
    return 0;
}

Literals class

  1. Data members are literal types of polymeric category belongs to the class literals.
  2. Other categories literals condition: members are literal data type; constexpr class must contain at least one constructor; if the class contains a data member of the initial value, the initial value of the built-type members must be a constant expression, or If the members belong to a certain class type, the initial value of the members themselves must be used constructor constexpr; class must define the default destructor, the member responsible for the destruction of the object class.
  3. Constexpr constructor function body is generally empty, all the data members must be initialized, the initial value or constexpr constructor, or a constant expression.
class Debug
{
public:
    constexpr Debug(bool b = true) : hw(b), io(b), other(b){};
    constexpr Debug(bool h, bool i, bool o) : hw(h), io(i), other(o){};
    constexpr bool any()
    {
        return hw | io | other;
    }
    void set_io(bool b)
    {
        io = b;
    }
    void set_hw(bool b)
    {
        hw = b;
    }
    void set_other(bool b)
    {
        other = b;
    }

private:
    bool hw;
    bool io;
    bool other;
};

7.6 Static class members

  1. Static members of a class related to the class, regardless of the object class.
  2. Static members can be public or private, can be a constant, reference, pointer, class type. It is no this pointer can not be declared const member functions.
  3. Static members are declared static within a class, visit with the scope operator. Member function can directly access static members.
  4. (Defined outside the class can not be duplicated when static) static member functions within the class or classes may be defined outside; static data members must be outside the class definition and initialization , and can only be defined and initialized once.
  5. static const int class member may be provided with an initial value; static constexpr must be provided with an initial value of the class.
  6. If the compiler may replace the value of a static member, static const constexpr static or may not be defined; if not, there must be a static member definition statement.
  7. Static members, references and pointers may be incomplete type (class declaration only temporarily undefined class), the class can access only after defining its general members, except for an incomplete type; static member can make a default argument, non-static data members not as a default argument.
Published 77 original articles · won praise 25 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_34801642/article/details/104874835