CPP Chapter 10:objects and Classes Part2

Source: Internet
Author: User

10.2.4 Using Classes

Following EXAPMLE uses the class definition and implementation written in previous files:

// usestok0.cpp -- the client program// compiler with stock00.cpp#include <iostream>#include "stock00.h"int main(){    Stock s;    s.acquire("NanoSmart", 20, 12.5);    s.show();    s.buy(15, 18.125);    s.show();    s.sell(400, 20.00);    s.show();    s.buy(300000, 40.125);    s.show();    s.sell(300000, 0.125);    s.show();    return 0;}

The code below is a client:
Client: A program, that uses the class
Server: The class declaration and the class methods

10.2.5 Changing the implementation

Output formatting features for cout:

Avoid e-notation

std::ios_base::fmtflags orig = std::cout.setf(std::ios_base::fixed, ios_base::floatfield); // set the format while store original format in orig...std::cout.setf(orig, std::ios_base::floatfield) // reset to original format

Set Output precision

std::streamsize prec = std::cout.precision(3); // save preceding precision in prec...std::cout.precision(prec);
10.2.6 reviewing our stories to date

Use member functions by applying membership operator (.) to Objects:object.func ();

10.3 Class Constructors and Destuctors

To accomplish initialization and declaration for class objects, C + + provides special member functions called class C Onstructors. In fact, a constructor have no return type, its name was often same to the class ' s name. For Example:constructor for class stock is stock ()

10.3.1 declaring and defining constructors

No return type, prototype goes in the public section:

// constructor prototype with default argumentsStock(const string & co, long n = 0, double pr = 0.0);

Next comes the definition of the constructor in separate file:

Stock::Stock(const string & co, long n, double pr){company = co;if (n < 0){    std::cerr << "Number of shares can‘t be negative; " << company << " shares set to 0.\n";    shares = 0;}else    shares = n;share_val = pr;set_tot();}

) A program automatically invokes the constructor when it declares a object
) Parameters of the constructor should not share name with the member data.

10.3.2 Using Constructors

There is explicit and implicit initialize objects with constructor:

Stock food = Stock("World Cabbage", 250, 1.25); // explicitStock garment("Furry Mason", 50, 2.5); // implicit

Whether calling the constructor function Stock () explicitly or use parentheses following an object ' s declaration is equiv Alent.

10.3.3 Default Constructors

If you don ' t provide any constructors, C + + automatically supplies a default constructor:

Stock::Stock() {}

When you initialize a object without initialization, you is just leaving all of its member data uninitialized:

Stock s; // values of s member data are uninitialized

) could provide you own version of the default constructor by 2 ways:
1 default Arguments:set All arguments to is default arguments in the constructor:

Stock(const string & co = "Error", int n = 0, double pr = 0.0);

2 Use function overloading to define a second constructor with no arguments:

Stock::Stock(){    company = "no name";    shares = 0;    share_val = 0.0;    total_val = 0.0;}

If you have provided a nondefault constructor without providing a default one, the declaration like this is an error:

Stock s; // not possible with current constructor

So it's usually correct to provide a default constructor with a nondefault one
) Examples of using constructors:

Stock first; // calls default constructor implicitlyStock first = Stock(); // calls default constructor explicitlyStock *prelief = new Stock; // calls default constructor implicitlyStock first("Concrete Conglomerate"); // calls constructorStock second(); // !!! declares a function!!!Stock third; // calls default constructor

When you implicitly call the default constructor, you don ' t use parentheses (difference between line 5 and line 6 in the CO De above)

10.3.4 Destructors

A destructor is called automatically when a class object expires. A destructor have a special name:formed by the class name preceded by a tilde (~):

~Stock();

No return value, no declared type and no arguments for destructors.
You have 2 ways of having a destructor:

    1. The compiler generates an implicit, do-nothing destructor.

    2. You provide definition for the destructor, no matter do-nothing type:
Stock::~Stock(){}

or do-something type:

Stock::~Stock(){    cout << "Bye,  " << company << "!\n";}
10.3.5 Improving the Stock class

) Major changes to the three files:
1 Adds Constructors and destructors, removing unnecessary acquire () function
2 Format the output in Stock::show ()
3 Refine the object-declaration syntax

  void stock::buy (Long num, double price) {if (num < 0) {Std::cout << "number of shares Pu Rchased can ' t be negative.    "<<" Transaction is aborted.\n ";        } else {shares + = num;        Share_val = Price;    Set_tot ();    }}void Stock::sell (Long num, double price) {using Std::cout; if (num < 0) {cout << "number of shares sold can ' t be negative.    Transaction is aborted.\n "; } else if (num > Shares) {cout << "You can ' t sell more than you have!    Transaction is aborted.\n ";        } else {shares-= num;        Share_val = Price;    Set_tot ();    }}void stock::update (double price) {share_val = Price; Set_tot ();} void Stock::show () {std::cout << ' Company: ' << company << ' Shares: ' << Shares << ' \ n '    ; Std::cout << "Shares Price: $" << share_val << "Total Worth: $" << total_val << "\ n";} 
Stock10.cpp--stock class with constructors, destructor Added#include <iostream> #include "stock10.h" Stock::    Stock () {std::cout << "Default constructor called\n";    Company = "No Name";    Shares = 0;    Share_val = 0.0; Total_val = 0.0;} Stock::stock (const std::string & Co, long N, double pr) {std::cout << "Constructor using" << Co &LT;&L T    "Called\n";    Company = CO;  if (n < 0) {Std::cout << "number of shares can ' t is negative;" << company << "shares set        To 0.\n ";    Shares = 0;    } else shares = N;    Share_val = PR; Set_tot ();} Stock::~stock () {std::cout << "Bye," << company << "!\n";} void Stock::buy (Long num, double price) {if (num < 0) {Std::cout << "number of shares purchased can ' t be negative.    "<<" Transaction is aborted.\n ";        } else {shares + = num;        Share_val = Price;    Set_tot (); }}void Stock::sell (loNg num, double price) {using Std::cout; if (num < 0) {cout << "number of shares sold can ' t be negative.    Transaction is aborted.\n "; } else if (num > Shares) {cout << "You can ' t sell more than you have!    Transaction is aborted.\n ";        } else {shares-= num;        Share_val = Price;    Set_tot ();    }}void stock::update (double price) {share_val = Price; Set_tot ();}    void Stock::show () {using Std::cout;    Using Std::ios_base;    Ios_base::fmtflags orig = COUT.SETF (ios_base::fixed, Ios_base::floatfield);    Std::streamsize Prec = cout.precision (3);    cout << ' Company: ' << company << ' Shares: ' << Shares << ' \ n ';    cout << "Share Price: $" << share_val;    Cout.precision (2);    cout << "Total Worth: $" << total_val << "\ n";    COUT.SETF (orig, Ios_base::floatfield); Cout.precision (PREC);}
// usestock1.cpp -- using the Stock class// compile with stock10.cpp#include <iostream>#include "stock10.h"int main(){    { // 1111111        using std::cout;        cout << "Using constructors to create new objects\n";        Stock stock1("NanoSmart", 12, 20.0);        stock1.show();        Stock stock2 = Stock("Boffo Objects", 2, 2.0);        stock2.show();        cout << "Assigning stock1 to stock2:\n";        stock2 = stock1;        cout << "Listing stock1 and stock2:\n";        stock1.show();        stock2.show();        cout << "Using a constructor to reset an object\n";        stock1 = Stock("Nifty Foods", 10, 50.0);        cout << "Revised stock1:\n";        stock1.show();        cout << "Done\n";    } // 1111111    return 0;}

The result of the code:

) Noteworthy:
1 Extra braces were used (in Usestok1.cpp where 1111111 occurs). In windowing environment, the window would close before the last of the destructor calls, preventing you from seeing the last "Bye, nanosmart!" and "Bye, Nifty foods!"
2 The following code:

Stock stock2 = Stock("Boffo Objects", 2, 2.0);

C + + actually have ways to execute this:one are to let it behave like the following syntax:

Stock stock2("Boffo Objects", 2, 2.0);

The second is to create a temporary object which are then copied to Stock2, which would cause the destructor call for Tempor Ary object. As a result, you'll see output of ' Bye, Boffo Objects ' after the compiler calls the constructor, (which is kind of weird for me lol)
3 could do object assignment:

stock2 = stock1;

4 Analyze following code:

stock1 = Stock("Nifty Foods", 10, 50.0);

Stock1 already exists, so here the compiler create a temporary object of the Stock which are later copied to Stock1 to rewrite The contents of Stock1. In the This is the could also use constructors to reassign objects.
5 in the output this could is observed:

Bye, NanoSmart!Bye, Nifty Foods!

Remember that those automatic variables go on a stack which follows the principle of LIFO Out), so the destructor are also called to delete them in the LIFO order
6 Choose initialization rather than assignment if possible (more efficient):

Stock stock2 = Stock("thing", 2, 2.0); // initialization invoked, doesn‘t create temporary objectsstock1 = Stock("thing2", 3, 2.0); // assignment invoked, create temporary objects

) You could also use list initialization with objects (those with braces):

Stock hot_tip = {"Derivatives Plus Plus", 100, 45.0};Stock temp {};

Const member functions

const Stock land = Stock("thing");land.show();

The compiler would reject the second line because Stock::shoe () doesn ' t promise don't to alter the data, where land is a con St object. Solution is to place the const keyword after the function parentheses:

void show() const; // prototyp3void stock::show() const // providing definition{    ...}

Class functions declared and defined in the this is called Const member functions.

10.4 Knowing your objects:the this pointer

) Consider defining a member function that looks at both the Stock objects and return the reference to the "the"

const Stock & topval(const Stock & s) const;

The first const says that it returns a reference to a const object and the second const shows that the argument object ' s Valu E can ' t be altered, the third const promises, the function would not alter the data of the invoking object.
The function accesses one object implicitly (the invoking object) and one object explicitly (the argument object).
A Special Pointer This was used to access the invoking object. The This is pointer points to the object used to invoke a member function. To access the invoking object's members, use Operator ",":

cout << this->total_val; // use -> to access data from pointer to structures or classes

When returning a reference to the invoking object, **return (*this) * * As the invoking object. Complete definition of the comparison member function:

const Stock & Stock::topval(const Stock & s) const{    if (s.total_val > total_val)        return s;    else        return *this;}

Here comes revised version of class declaration and implementation files:

  #ifndef stock20_h_included#define stock20_h_included#include <string>class stock{private:std::    String Company;    Long shares;    Double Share_val;    Double Total_val; void Set_tot () {total_val = shares * SHARE_VAL;} Public:stock (); Default constructor Stock (const std::string & Co, long n = 0, double PR = 0.0); Constructor ~stock ();    destructor void buy (long num, double price);    void sell (Long num, double price);    void update (double price);    void Show (); Const STOCK & Topval (const stock & S) const;}; #endif//stock20_h_included  
#ifndef STOCK20_H_INCLUDED#define STOCK20_H_INCLUDED#include <string>class Stock{private:    std::string company;    long shares;    double share_val;    double total_val;    void set_tot() {total_val = shares * share_val; }public:    Stock(); // default constructor    Stock(const std::string & co, long n = 0, double pr = 0.0); // constructor    ~Stock(); // destructor    void buy(long num, double price);    void sell(long num, double price);    void update(double price);    void show();    const Stock & topval(const Stock & s) const;};#endif // STOCK20_H_INCLUDED

CPP Chapter 10:objects and Classes Part2

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.