过程性编程和面向对象编程
//stock00.h -- Stock class interface
//version 00
#ifndef STOCK00_H_
#define STOCK00_H_
#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:
void acquire(const std::string& co, long n, double pr);
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
void show();
};// note semicolon at the end
#endif
不必在类声明中使用关键字private,因为这是类对象的默认访问控制:
class World{
float mass; // private by default
char name[20];
public:
void tellall(void);
}
//stock00.cpp -- implementing the Stock class
//version 00
#include <iostream>
#include "stock00.h"
void Stock::acquire(const std::string& co, long n, double pr) {
company = co;
if (n < 0) {
std::cout << "Number of shares can't be negativer; "
<< company << " shares set to 0.\n";
shares = 0;
}
else {
shares = n;
}
share_val = pr;
set_tot();
}
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() {
std::cout << "Company: " << company
<< " Shares: " << shares << "\n"
<< " Share price: $" << share_val
<< " Total Worth: $" << total_val << std::endl;
}
//usestck0.cpp -- the client program
//compile with stock00.cpp
#include <iostream>
#include "stock00.h"
int main() {
Stock fluffy_the_cat;
fluffy_the_cat.acquire("NanoSmart", 20, 12.50);
fluffy_the_cat.show();
fluffy_the_cat.buy(15, 18.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(400, 20.00);
fluffy_the_cat.show();
fluffy_the_cat.buy(30000, 40.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(30000, 0.125);
fluffy_the_cat.show();
return 0;
}
如果构造函数使用new来分配内存,则析构函数使用delete来释放内存。
如果创建的是静态存储类对象,则其析构函数将在程序执行完代码块时自动被调用。如果创建的是自动存储类对象,则其析构函数将在程序执行完代码块时自动被调用。如果对象是通过new创建的,则它将驻留在栈内存或自由存储区中,当使用delete来释放内存时,其析构函数将自动被调用。
const成员函数
请看下面的代码片段
const Stock land = Stock("Kludgehorn Properties");
land.show();
对于当前的C++来说,编译器会拒绝第二行。因为show()的代码无法确保调用对象不被修改——调用对象应该和const一样,不应被修改。这里需要一种 新的语法,保证函数不会被修改调用对象。C++的解决方法是
void show() const; //promise not to change invoking object
函数定义的开头应该这样:
void stock::show() const;
this指针
const Stock& Stock::topval(const Stock & s) const{
if(s.total_val > total_val){
return s;
}else{
return *this;
}
}
this指针指向用来调用成员函数的对象。
// stack.h -- class definition for the stack ADT
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack {
private:
enum
{
MAX = 10
}; //constant specific to class
Item items[MAX]; //holds stack items
int top; //index for top stack item
public:
Stack();
bool isEmpty() const;
bool isfull() const;
//push() return false if stack already is full, true otherwise
bool push(const Item& item);
///pop() return false if stack already is full, true otherwise
bool pop(Item& item);
};
#endif // STACK_H_
//stack.cpp -- Stack member functions
#include "stack.h"
Stack::Stack() { //create an empty stack
top = 0;
}
bool Stack::isEmpty() const {
return top == 0;
}
bool Stack::isfull() const {
return top == MAX;
}
bool Stack::push(const Item& item) {
if (top < MAX) {
items[top++] = item;
return true;
}
else {
return false;
}
}
bool Stack::pop(Item& item) {
if (top > 0) {
item = items[--top];
return true;
}
else {
return false;
}
}
// stacker.cpp -- testing the stack class
#include <iostream>
#include <cctype>
#include "stack.h"
int main() {
using namespace std;
Stack st;
char ch;
unsigned long po;
cout << "Please enter A to add a purchase order,\n" <<
"P to process a PO, or Q to quit.\n";
while (cin >> ch && toupper(ch) != 'Q')
{
while (cin.get() != '\n') {
continue;
}
if (!isalpha(ch)) {
cout << ' \a';
continue;
}
switch (ch)
{
case 'A':
case 'a':
cout << "Enter a PO number to add: ";
cin >> po;
if (st.isfull())
cout << "stack already full\n";
else
st.push(po);
break;
case 'P':
case 'p':
if (st.isEmpty()) {
cout << "stack already empty\n";
}
else {
st.pop(po);
cout << "PO # " << po << " popped\n";
}
break;
default:
break;
}
cout << "Please enter A to add a purchase order,\n" <<
"P to process a PO, or Q to quit.\n";
cout << "Bye\n.";
return 0;
}
}