Reading Notes - C++ Primer, 4th Edition

Reading Notes - C++ Primer, 4th Edition

class Sales_item {
public:
    // operations on Sales_item objects
    double avg_price() const;
    bool same_isbn(const Sales_item &rhs) const
        { return isbn == rhs.isbn; }
    // default constructor needed to initialize members of built-in type
    Sales_item(): units_sold(0), revenue(0.0) { }
private:
    std::string isbn;
    unsigned units_sold;
    double revenue;
};

double Sales_item::avg_price() const
{
    if (units_sold)
        return revenue/units_sold;
    else
        return 0;
}
  • Const keyword used in the member function declarartion of a class definition:
    • const member may not change the data member of the objects on which it operates.
    • const should appear in both the declaration and the definition, otherwise the compliler will report the error.
  • Accesss Labels:
    • Member defined after a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members.
    • Member defined after a private label are not accessible to code that uses the class. The private sections encapsulate (e.g., hide) the implementation from code that uses the type.
    • For those members without the explicit access label:
      • Struct: default as public.
      • Class: default as private.
  • Internal state of the class is often designed as private. Only a member function could be responsible for the state transition error. It greatly eases the problems of maintenance and the program correctness.

你可能感兴趣的:(Reading Notes - C++ Primer, 4th Edition)