习题选自:C++ Primer Plus(第六版) 内容仅供参考,如有错误,欢迎指正 !
类是用户定义的类型的定义。类声明指定了数据将如何存储,同时提供了访问和操作这些数据的方法。
用户可以根据类的公有接口对类对象执行的操作,这是抽象。类的数据成员可以是私有的(默认值),这意味着只能通过类成员函数来对数据进行访问,这是数据隐藏。实现的具体细节(如数据的表示和方法的代码)都是隐藏的,这是封装。
类定义了一种类型,包括如何使用它。对象是一个变量或其他的数据对象(如new生成的),并根据类定义被创建和使用。类和对象之间的关系同标准类型与其变量之间的关系。
如果创建给定类的多个对象,则每个对象都有其自己的数据内存空间;但所有的对象都使用同一组成员函数(通常,这个方法是公有的,而数据是私有的,但这只是策略方面的问题,而不是对类的要求)
#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <string>
using namespace std;
class BankAccount
{
private:
std::string name_str;
std::string accountNum_str;
double balance;
public:
BankAccount(const string &name, const string &accountNum, double bal = 0.0);
void show();
void deposit(double cash);
void withdraw(double cash);
};
#endif
在创建类对象或显示调用构造函数时,类的构造函数被调用。当函数过期时,析构函数被调用。
#include "BankAccount.h"
#include <iostream>
using namespace std;
BankAccount::BankAccount(const string &name, const string &accountNum, double bal)
{
name_str = name;
accountNum_str = accountNum;
balance = bal;
}
void BankAccount::show()
{
cout << "Account Name : " << name_str << endl;
cout << "Account Number : " << accountNum_str << endl;
cout << "Account Balance : " << balance << endl;
}
void BankAccount::withdraw(double cash)
{
balance -= cash;
}
void BankAccount::deposit(double cash)
{
balance += cash;
}
默认构造函数是没有参数或所有参数都有默认值的构造函数。拥有默认构造函数后,可以声明对象,而不初始化它,即使已经定义了初始化构造函数。它还使得能够声明数组。
原stock20.h的版本:
//Listing 10.7 stock20.h
// stock20.h -- augmented version
#ifndef STOCK20_H_
#define STOCK20_H_
#include <string>
class Stock
{
private:
std::string company;
int 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);
~Stock(); // do-nothing destructor
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
void show() const;
const Stock &topval(const Stock &s) const;
};
#endif
修改后:
#ifndef STOCK20_H_
#define STOCK20_H_
#include <string>
class Stock
{
private:
std::string company;
int shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val; }
public:
Stock();
Stock(const std::string &co, long n = 0, double pr = 0.0);
~Stock();
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
void show() const;
const Stock &topval(const Stock &s) const;
int shares() const { return shares; }
double shareVal() const { return share_val; }
double totalVal() const { return total_val; }
const std::string &comp_name() const { return company; }
};
#endif
this指针是类方法可以使用的指针,它指向用于调用方法的对象。因此,this是对象的地址,*this是对象本身。
BankAccount.h:
#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <string>
using namespace std;
class BankAccount
{
private:
std::string name_str;
std::string accountNum_str;
double balance;
public:
BankAccount(const string &name, const string &accountNum, double bal = 0.0);
void show();
void deposit(double cash);
void withdraw(double cash);
};
#endif
BankAccount.cpp:
#include "BankAccount.h"
#include <iostream>
using namespace std;
BankAccount::BankAccount(const string &name, const string &accountNum, double bal)
{
name_str = name;
accountNum_str = accountNum;
balance = bal;
}
void BankAccount::show()
{
cout << "Account Name : " << name_str << endl;
cout << "Account Number : " << accountNum_str << endl;
cout << "Account Balance : " << balance << endl;
}
void BankAccount::withdraw(double cash)
{
balance -= cash;
}
void BankAccount::deposit(double cash)
{
balance += cash;
}
main.cpp:
#include "BankAccount.h"
#include <iostream>
using namespace std;
int main()
{
string name, account;
double num;
cout << "enter name : ";
getline(cin, name);
cout << "enter bank account : ";
getline(cin, account);
BankAccount ba(name, account);
cout << "enter the deposit amount : ";
cin >> num;
cin.get();
ba.deposit(num);
cout << "your current bank account information : ";
ba.show();
cout << "enter the withdrawal amount: ";
cin >> num;
cin.get();
ba.withdraw(num);
cout << "your current bank account information : ";
ba.show();
return 0;
}
class Person
{
private:
static const int LIMIT = 25;
string lname; // Person’s last name
char fname[LIMIT]; // Person’s first name
public:
Person()
{
lname = "";
fname[0] = '\0';
} // #1
Person(const string &ln, const char *fn = "Heyyou"); // #2
// the following methods display lname and fname
void Show() const; // firstname lastname format
void FormalShow() const; // lastname, firstname format
};
Person one; // use default constructor
Person two("Smythecraft"); // use #2 with one default argument
Person three("Dimwiddy", "Sam"); // use #2, no defaults one.Show();
cout << endl;
one.FormalShow();
// etc. for two and three
Person.h :
#ifndef PERSON_H
#define PERSON_H
#include <string>
using std::string;
class Person
{
private:
static const int LIMIT = 25;
string lname; // Person’s last name
char fname[LIMIT]; // Person’s first name
public:
Person()
{
lname = "";
fname[0] = '\0';
} // #1
Person(const string &ln, const char *fn = "Heyyou"); // #2
// the following methods display lname and fname
void Show() const; // firstname lastname format
void FormalShow() const; // lastname, firstname format
};
#endif
Person.cpp :
#include "Person.h"
#include <iostream>
using std::cout;
using std::endl;
Person::Person(const string &ln, const char *fn)
{
lname = ln;
strcpy(fname, fn);
}
void Person::FormalShow() const
{
cout << fname << " " << lname << endl;
}
void Person::Show() const
{
cout << fname << " , " << lname << endl;
}
main.cpp :
#include "Person.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
Person one;
Person two("Smythecraft");
Person three("Dimwiddy", "Sam");
cout << "Person one : " << endl;
one.Show();
one.FormalShow();
cout << "Person two : " << endl;
two.Show();
two.FormalShow();
cout << "Person two : " << endl;
three.Show();
three.FormalShow();
return 0;
}
Golf.h:
#ifndef GOLF_H
#define GOLF_H
class Golf
{
public:
Golf();
Golf(const char *name, int hc);
int setgolf();
void sethandicap(int hc);
void showgolf() const;
private:
static const int Len = 40;
char fullname[Len];
int handicap;
};
#endif
Golf.cpp:
#include "Golf.h"
#include <iostream>
using namespace std;
Golf::Golf()
{
strcpy(fullname, "DefaultName");
handicap = 0;
}
Golf::Golf(const char *name, int hc)
{
strcpy(fullname, name);
handicap = hc;
}
int Golf::setgolf()
{
cout << "please enter fullname : ";
cin.getline(fullname, Len);
if (strlen(fullname) == 0)
return 0;
else
{
cout << "please enter handicap : ";
cin >> handicap;
cin.get();
return 1;
}
}
void Golf::sethandicap(int hc)
{
handicap = hc;
}
void Golf::showgolf() const
{
cout << "fullname : " << fullname << ", handicap : " << handicap << endl;
}
main.cpp:
#include "Golf.h"
#include <iostream>
using namespace std;
int main()
{
Golf ann("Ann Birdfree", 24), andy, arrGolf[3];
ann.showgolf();
andy.showgolf();
andy.setgolf();
andy.showgolf();
andy.sethandicap(20);
andy.showgolf();
int i = 0;
while (i < 3 && arrGolf[i].setgolf())
{
arrGolf[i].showgolf();
i++;
if (i < 3)
cout << "next one: " << endl;
}
return 0;
}
sales.h:
//sales.h-----头文件
#ifndef SALES_H
#define SALES_H
namespace SALES
{
const int QUARTERS = 4;
class Sales
{
public:
Sales();
Sales(const double ar[], int n);
void showSales();
private:
double sales[QUARTERS];
double average;
double max;
double min;
};
}
#endif
sales.cpp:
//sales.cpp-----源代码文件
#include "sales.h"
#include <iostream>
using namespace std;
namespace SALES
{
Sales::Sales(const double ar[], int n)
{
double min = 0, max = 0, sum = 0;
min = max = ar[0];
for (int i = 0; i < n; i++)
{
sales[i] = ar[i];
sum += ar[i];
if (ar[i] > max)
{
max = ar[i];
}
if (ar[i] < min)
{
min = ar[i];
}
}
average = sum / n;
}
Sales::Sales()
{
cout << "Please enter 4 quarters for sales:" << endl;
cout << "the 1 quarter :";
cin >> sales[0];
min = max = sales[0];
for (int i = 1; i < 4; i++)
{
cout << "the " << i << " quarter :";
cin >> sales[i];
if (max < sales[i])
{
max = sales[i];
}
if (min > sales[i])
{
min = sales[i];
}
}
average = (sales[0] + sales[1] + sales[2] + sales[3]) / 4;
}
void Sales::showSales()
{
cout << "Display all information in sales : " << endl;
cout << "The 4 quarters are $" << sales[0] << ", $" << sales[1] << ", $" << sales[2] << ", $" << sales[3] << endl;
cout << "The average income is $" << average << endl;
cout << "The maximum income is $" << max << endl;
cout << "The minimum income is $" << min << endl;
}
}
main.cpp:
#include "sales.h"
#include <iostream>
using namespace SALES;
int main()
{
double arr[4] = {3.4, 5.6, 2.5, 6.1};
Sales s1(arr, 4);
s1.showSales();
Sales s2;
s2.showSales();
return 0;
}
struct customer {
char fullname[35];
double payment;
};
stack.h :
#ifndef STACK_H
#define STACK_H
struct customer
{
char fullname[35];
double payment;
};
typedef customer Item;
class Stack
{
public:
Stack();
bool pop(Item &it);
bool push(const Item &it);
bool isfull() const;
bool isempty() const;
private:
double total;
int top;
enum
{
MAX = 10
};
Item item[MAX];
};
#endif
stack.cpp :
#include "stack.h"
#include <iostream>
using namespace std;
Stack::Stack()
{
top = 0;
total = 0;
}
bool Stack::isempty() const
{
return top == 0;
}
bool Stack::isfull() const
{
return top == MAX;
}
bool Stack::pop(Item &it)
{
if (top > 0)
{
it = item[--top];
total += it.payment;
cout << "An order has been processed, current total revenue : " << total << endl;
return true;
}
else
{
return false;
}
}
bool Stack::push(const Item &it)
{
if (top < MAX)
{
item[top++] = it;
return true;
}
else
{
return false;
}
}
main.cpp :
#include "stack.h"
#include <iostream>
using namespace std;
int main()
{
Stack stack;
customer cu;
char ch;
cout << "Press a to add a customer, P to process an order, and Q to exit." << endl;
while (cin >> ch && toupper(ch) != 'Q')
{
while (cin.get() != '\n')
{
continue;
}
if (!isalpha(ch))
{
cout << '\a';
continue;
}
switch (ch)
{
case 'a':
case 'A':
if (stack.isfull())
{
cout << "The order of 10 customers has been filled. Please process the existing order first !" << endl;
}
else
{
cout << "Add customer name : ";
cin.getline(cu.fullname, 35);
cout << "Add the customer's consumption amount : ";
cin >> cu.payment;
cout << "dsssd : " << stack.push(cu);
}
break;
case 'p':
case 'P':
if (stack.isempty())
{
cout << " There are currently no unprocessed orders." << endl;
}
else
{
stack.pop(cu);
}
break;
default:
cout << " Input error!!!" << endl;
break;
}
cout << "Press a to add a customer, P to process an order, and Q to exit." << endl;
}
return 0;
}
class Move
{
private:
double x;
double y;
public:
Move(double a = 0, double b = 0); //sets x, y to a, b
showmove() const; // shows current x, y values
Move add(const Move &m) const;
// this function adds x of m to x of invoking object to get new x,
// adds y of m to y of invoking object to get new y, creates a new
// move object initialized to new x, y values and returns it
reset(double a = 0, double b = 0); // resets x,y to a, b
}
move.h :
#ifndef MOVE_H
#define MOVE_H
class Move
{
private:
double x;
double y;
public:
Move(double a = 0, double b = 0); //sets x, y to a, b
void showmove() const; // shows current x, y values
Move add(const Move &m) const;
// this function adds x of m to x of invoking object to get new x,
// adds y of m to y of invoking object to get new y, creates a new
// move object initialized to new x, y values and returns it
void reset(double a = 0, double b = 0); // resets x,y to a, b
};
#endif
move.cpp :
#include "move.h"
#include <iostream>
Move::Move(double a, double b)
{
x = a;
y = b;
}
Move Move::add(const Move &m) const
{
return Move(x + m.x, y + m.y);
}
void Move::showmove() const
{
std::cout << "x is :" << x << std::endl;
std::cout << "y is :" << y << std::endl;
}
void Move::reset(double a, double b)
{
x = a;
y = b;
}
main.cpp :
#include "move.h"
#include <iostream>
int main()
{
Move m1(1, 2), m2(3, 4);
m1.showmove();
m2.showmove();
m1.add(m2).showmove();
m1.reset(5, 6);
m1.showmove();
return 0;
}
plorg.h :
#ifndef PLORG_H
#define PLORG_H
class Plorg
{
private:
char name[19];
int CI;
public:
Plorg();
Plorg( const char *n, int ci);
void show();
void setCI(int ci);
};
#endif
plorg.cpp :
#include "plorg.h"
#include <iostream>
Plorg::Plorg()
{
strcpy(name, "Plorg");
CI = 0;
}
Plorg::Plorg(const char *n, int ci)
{
strcpy(name, n);
CI = ci;
}
void Plorg::setCI(int ci)
{
CI = ci;
}
void Plorg::show()
{
std::cout << "name : " << name << ", CI: " << CI << std::endl;
}
main.cpp :
#include "plorg.h"
#include <iostream>
int main()
{
Plorg p1, p2("plorg2", 50);
p1.show();
p2.show();
p1.setCI(30);
p1.show();
}
void visit(void (*pf) (Item&));
list.h :
#ifndef LIST_H
#define LIST_H
typedef int Item;
const int MAX = 10;
class List
{
private:
Item ITEM[MAX];
int COUNT;
public:
List();
bool isfull();
bool isempty();
bool addItem(Item it);
Item *item();
int count();
void visit(void (*pf)(Item &));
};
#endif
list.cpp :
#include "list.h"
#include <iostream>
List::List()
{
COUNT = 0;
}
bool List::isfull()
{
return COUNT == MAX;
}
bool List::isempty()
{
return COUNT == 0;
}
bool List::addItem(Item it)
{
if (this->isfull())
{
std::cout << "full already, add fail. " << std::endl;
return false;
}
else
{
ITEM[COUNT++] = it;
return true;
}
}
Item *List::item()
{
return ITEM;
}
int List::count()
{
return COUNT;
}
void List::visit(void (*pf)(Item &))
{
for (int i = 0; i < COUNT; i++)
{
(*pf)(ITEM[i]);
}
}
main.cpp :
#include "list.h"
#include <iostream>
void intadd2(int &n);
int main()
{
List l;
l.addItem(1);
l.addItem(2);
l.addItem(3);
for (int i = 0; i < 3; i++)
{
std::cout << l.item()[i] << std::endl;
}
l.visit(intadd2);
for (int i = 0; i < 3; i++)
{
std::cout << l.item()[i] << std::endl;
}
return 0;
}
void intadd2(int &n)
{
n += 2;
}