Inheritance (inheritance) and dynamic binding are an important component of object-oriented, that is, inheritance (inheritance) and polymorphism (polymorphism),
You can make a derived class (derived class) an interface (interface) that has a base class ();
Derived classes can overwrite (override) The virtual functions of the base class (virtual function) to conform to specific functions;
Derived classes can be implicitly converted to base classes (derived-to-base conversion), but not reversible, because the objects of the derived class contain portions of their own parts and objects of the base class;
Try to use the constructor of the base class to construct the object of the base class, which can be easily managed; For static members, define only (define) once, ignoring other definitions;
You can show that the definition class cannot be inherited, adding a "final" qualifier after the class;
Code:
* * * CppPrimer.cpp * * Created on:2013.11.12 * author:caroline//*eclipse cdt*/#includ
E <iostream> #include <string> #include <cstddef> using namespace std;
Class Quote {public:quote () = default; Quote (const std::string& book, double sales_price): Bookno (book), Price (Sales_price) {} Std::strin
G ISBN () const {return bookno;} Virtual Double Net_price (std::size_t N) const {return n price;}//virtual function virtual ~quote () = default;
Dynamic binding destructor private:std::string Bookno;
Protected://protected type Double price = 0.0;
};
Class Bulk_quote Final:public Quote {//final Qualifier, cannot be inherited public:bulk_quote () = default; Bulk_quote (const Std::string&book, double p, std::size_t qty, double disc): Quote (book, p), Min_qty (qty), D
Iscount (disc) {}///Use base class's constructor double Net_price (std::size_t cnt) const override; Private:std::size_t min_qty = 0; Minimum amount of discount double discount = 0.0;
Discount}; Double Bulk_quote::net_price (std::size_t cnt) const {if (CNT >= min_qty) return cnt * (1-discount) * p
Rice
else return CNT * price;
int main (void) {Quote Q ("Cppprimer", 99);
Bulk_quote BQ ("Cppprimer", 99, 10, 0.5);
std::size_t n = 20;
Std::cout << "We want to buy" << N << "books." << Std::endl;
Std::cout << "Quote net_price:" << q.net_price (n) << Std::endl;
Std::cout << "Bulk_quote net_price:" << bq.net_price (n) << Std::endl;
return 0; }
Author: csdn Blog spike_king
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/