Transaction::Transaction() // implementation of { // base class ctor ... logTransaction(); // as final action, log this } // transaction
class BuyTransaction: public Transaction { // derived class public: virtual void logTransaction() const; // how to log trans- // actions of this type ... };
class SellTransaction: public Transaction { // derived class public: virtual void logTransaction() const; // how to log trans- // actions of this type ... }; 考虑执行这行代码时会发生什么:
class Transaction { public: eXPlicit Transaction(const std::string& logInfo);
void logTransaction(const std::string& logInfo) const; // now a non- // virtual func ... };
Transaction::Transaction(const std::string& logInfo) { ... logTransaction(logInfo); // now a non- } // virtual call
class BuyTransaction: public Transaction { public: BuyTransaction( parameters ) : Transaction(createLogString( parameters )) // pass log info { ... } // to base class ... // constrUCtor