|
Example:
public class BankAccount
{
private double balance;
// Constructors
public BankAccount()
{
balance = 0;
}
public BankAccount(double x)
{
balance = x;
}
// Ordinary methods
public void deposit(double amount)
{
balance = balance + amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public double getBalance()
{
return(balance);
}
}
|
import BankAccount; // <--- Must be done.
// Java made it easy: put class in same directory
// and Java will look for the class to import
public class myProgram
{
main()....
}
|
|
Example:
class BankAccount
{
private:
double balance;
public:
// Constructors
BankAccount()
{
balance = 0;
}
BankAccount(double x)
{
balance = x;
}
// Ordinary methods
void deposit(double amount)
{
balance = balance + amount;
}
void withdraw(double amount)
{
balance = balance - amount;
}
double getBalance()
{
return(balance);
}
};
|
#include "BankAccount.C" // Need to include class declaration/definition
int main(int argc, char *argv[])
{
BankAccount x, y(1000);
cout << "x = " << x.getBalance() << endl;
cout << "y = " << y.getBalance() << endl;
x.deposit(100);
y.withdraw(100);
cout << "x = " << x.getBalance() << endl;
cout << "y = " << y.getBalance() << endl;
}
|
How to run:
CC TestBankAccount.C
a.out
|
The declaration part and the definition part are usually stored in separate files
class BankAccount
{
private:
double balance;
public:
// Constructors
BankAccount();
BankAccount(double x);
// Ordinary methods
void deposit(double amount);
void withdraw(double amount);
double getBalance();
};
|
This is stored in BankAccount.h (this is usually called a header file)
include "BankAccount.h" // Include declaration first !
// Constructors
BankAccount::BankAccount()
{
balance = 0;
}
BankAccount::BankAccount(double x)
{
balance = x;
}
// Ordinary methods
void BankAccount::deposit(double amount)
{
balance = balance + amount;
}
void BankAccount::withdraw(double amount)
{
balance = balance - amount;
}
double BankAccount::getBalance()
{
return(balance);
}
};
|
(The BankAccount:: notation tells C++ that the function/method is a member method in the class BankAccount)
#include "BankAccount.h" // Need to include class declaration/definition
^^^^ (declaration file)
int main(int argc, char *argv[])
{
BankAccount x, y(1000);
cout << "x = " << x.getBalance() << endl;
cout << "y = " << y.getBalance() << endl;
x.deposit(100);
y.withdraw(100);
cout << "x = " << x.getBalance() << endl;
cout << "y = " << y.getBalance() << endl;
}
|
How to run:
CC -c BankAccount.C
CC -c TestBankAccount.C
CC TestBankAccount.o BankAccount.o
or:
CC BankAccount.C TestBankAccount.C
Run:
a.out
|