Stock

//Stock.h

#ifndef__STOCK_H__

#define__STOCK_H__

Const int NAME_SIZE=20;

Class Stock

{

Public:

Stock(char* szName, double dValue, int nNum);

void Buy(int nAdd);

double Sell(int nSold);

Private:

char* n_szName;

char m_szName[NAME_SIZE+1];

double m_dPrice;

int m_nNumber

Public:

void SetPrice(double dPrice);

const double GetPrice()const;

};

#endif

OR

Class Stock

{

Public:

Stock(char* szName, double dValue, int nNum);

~stock(): //to clean up memory

void Buy(int nAdd);

double Sell(int nSold);

Private:

char* n_szName;

double m_dPrice;

int m_nNumber

Public:

void SetPrice(double dPrice);

const double GetPrice()const;

};

#endif

//Stock.cpp

#include "Stock.h"

Stock::stock(char*, szName, double dValue, int nNum)

{

m_nNumber=nNum;

m_dPrice = dValue;

strncpy(m_szName, szName, NAME_SIZE);

m_szName[NAME_SIZE]= ‘\0’;

}

-don’t need to assign memory

-don’t need a destructor, compiler will give you one which is adequate

OR

Stock::stock(char*, szName, double dValue, int nNum)

{

m_nNumber=nNum;

m_dPrice = dValue;

m_szName = new char [strlen(szName) +1];

strcpy(m_szName,szName);

}

Stock::~Stock() //to clean up memory, deconstructor

{

delete[] m_szName;

}

<Accessor Functions>

void Stock::SetPrice(double dPrice)

{

m_dPrice=dPrice;

}

 

 

const double stock::GetPrice() const

{

return n_dPrice;

}

<Accessor Functions>

void Stock::Buy(int nAdd)

{

m_nNumber += nAdd;

}

 

 

double stock::Sell(int nSold)

{

assert(nSold <= m_nNumber);

double dValue = n_dPrice * nSold;

m_nNumber -= nSold;

return dValue;

}

#inlcude "stock.h"

int main()

{

Stock s("microsloth", 91.385,100);

s.Add(100;

double dCash = s.Sell(150);

 

(version using only SetPrice)

int main()

{

Stock s("microsloth", 91.385,100);

s.SetPrice(100.5);

if(sGetPrice()==100.5)

{

cout<<"C++Rocks!" << endl;

}

else

{

cout<<"VB Drools" <<endl;

}

Rules:

-use new-> delete in c++

-you can use malloc->freem but why?

-if you use malloc, don’t use delete

-if you use new,, don’t use free

Constructors (ctor)

-can take arguments

return no vlaue – not even null/void

-they can be explicitly or implictly called

-used for dat initialization

-method name: same as the class

Destructors (dtor)

-take no arguments

-return no values, not even void

-used for data cleanup

-method name: tilde followed by the name of the name of the class (~stock() )

-always called implicity

-if you don’t write one, the compiler will supply a "do nothing" dtor for you. –but, will not "delete" your memory.

 

 

 

Back | HOME | Next




Canpol Solutions Przeszukaj Katalog -- przeszukaj katalog / zamowienia, komentarze --  Poczta Polonijnej Witryny

Internet ExplorerUzywaj zawsze najnowszej przegladarki
M.I.E. lub, ewentualnie Netscape ktorej, niestety na razie nie polecamy..
Netscape


Canpol Solutions © Polonijna Witryna