C++Primer Plus筆記——第十二章 類和動態記憶體分配總結及程式清單
目錄
本章小結
本章介紹了定義和使用類的許多重要方面。其中的一些方面是非常微妙甚至很難理解的概念。如果其中的某些概念對於您來說過於複雜,也不用害怕——這些問題對於大多數C++的初學者來說都是很難的。 通常,對於諸如複製建構函式等概念,都是在由於忽略它們時遇到了麻煩後逐步理解的。本章介紹的一些內容乍看起來非常難以理解,但是隨著經驗越來越豐富,對其理解也將越透徹。
在類建構函式中,可以使用new為資料分配記憶體,然後將記憶體地址賦給類成員。這樣,類便可以處理長度不同的字串,而不用在類設計時提前固定陣列的長度。在類建構函式中使用new,也可能在物件過期時引發問題。如果物件包含成員指標,同時它指向的記憶體是由new分配的.則釋放用於儲存物件的記憶體並不會自動釋放物件成員指標指向的記憶體。因此在類建構函式中使用new類來分配記憶體時,應在類解構函式中使用delete來釋放分配的記憶體。這樣,當物件過期時,將自動釋放其指標成員指向的記憶體。
如果物件包含指向new分配的記憶體的指標成員,則將一個物件初始化為另—個物件,或將一個物件賦給另一個物件時,也會出現問題。在預設情況下,C++逐個對成員進行初始化和賦值,這意味著被初始化或被賦值的物件的成員將與原始物件完全相同。如果原始物件的成員指向一個數據塊,則副本成員將指向同一個資料塊。當程式最終刪除這兩個物件時,類的解構函式將試圖刪除同一個記憶體資料塊兩次,這將出錯。解決方法是:定義一個特殊的複製建構函式來重新定義初始化,並重載賦值運擇符。在上述任何一種 情況下,新的定義都將建立指向資料的副本,並使新物件指向這些副本。這樣,舊物件和新物件都將引用獨立的、相同的資料而不會重疊。由於同樣的原因,必須定義賦值運算子。對於每一種情況,最終目的都是執行深度複製,也就是說,複製實際的數裾,:而不僅僅是複製指向資料的指標。
物件的儲存持續性為自動或外部時,在它不再存在時將自動呼叫其解構函式。如使用new運算子為物件分配記憶體,並將其地址賦賦給一個指標,則當您將delete用於該指標時將自動為物件呼叫解構函式。然而,如果使用定位new運算子(而不是常規new運算子) 為類物件分配記憶體,則必須負責顯式地為該物件呼叫解構函式,方法是使用指向該物件的指標呼叫解構函式方法。C++允許在類中包含結構、類和列舉定義。這些巢狀型別的作用域是整個類,這意味著它們被侷限於類中,不會與其他地方定義的同名結構、類和枚舉發生衝突。
C++為類建構函式提供了一種可用來初始化資料成員的特殊語法。這種語法包括冒號和由逗號分隔的初始化列表,被放在建構函式引數的右括號後,函式體的左括號前。每一個初始化器都由被初始化的成員的名稱和包含初值的括號組成。從概念上說,這些初始化操作是在物件建立時進行的,此時函式體中的語句還沒有執行。語法如下;
queue(int qs) :qsize(qs),items(0),front(NULL),rear(NULL) {}
如果資料成員是非靜態const成員或引用,則必須採用這種格式,但可將C++11新增類內初始化用於非靜態const成員。
C++允許類內初始化,即在類定義中進行初始化:
class Queue
{
private:
...
Node * front = NULL;
enum {Q_SIZE = 10};
int items = 0;
const int qsize = Q_SIZE;
...
}
這與使用初始化列表等價。然而,使用成員初始化列表的建構函式將覆蓋相應的類內初始化。
程式清單
改進前的string類(在建構函式和解構函式中使用了動態記憶體分配)
12.1 strngbad.h
//strngbad.h -- flawed string class definition
#include <iostream>
#ifndef STRNGBAD_H_
#define STRNGBAD_H_
class StringBad
{
private:
char * str;
int len;
static int num_strings;
public:
StringBad(const char *s);
StringBad();
~StringBad();
friend std::ostream & operator << (std::ostream & os, const StringBad & st);
};
#endif // !STRNFBAD_H_
12.2 strngbad.cpp
//strngbad.cpp -- StringBad calss methods
#include <cstring>
#include "strngbad.h"
using namespace std;
int StringBad::num_strings = 0;
StringBad::StringBad(const char *s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
num_strings++;
cout << num_strings << ": \"" << str << "\" object created\n";
}
StringBad::StringBad()
{
len = 4;
str = new char[4];
strcpy(str, "C++");
num_strings++;
cout << num_strings << ": \"" << str << "\" default object created\n";
}
StringBad::~StringBad()
{
cout << "\"" << str << "\" object deleted\n";
--num_strings;
cout << num_strings << " left\n";
delete[]str;
}
ostream & operator << (ostream & os, const StringBad &st)
{
os << st.str;
return os;
return os;
}
12.3 vegnews.cpp
//vegnews.cpp -- using new and delete with classes
//compile with strngbad.cpp
#include <iostream>
#include "strngbad.h"
using namespace std;
void callme1(StringBad &);
void callme2(StringBad);
int main()
{
cout << "Startings an inner block.\n";
StringBad headline1("Celery Stalks at Midnight");
StringBad headline2("Lettuce Prey");
StringBad sports("Spinach Leaves Bowl for Dollars");
cout << "headline1: " << headline1 << endl;
cout << "headline2: " << headline2 << endl;
cout << "sports: " << sports << endl;
callme1(headline1);
cout << "headline1: " << headline1 << endl;
callme2(headline2);
cout << "headline1: " << headline1 << endl;
cout << "Initialize one object to another:\n";
StringBad sailor = sports;
cout << "sailor: " << sailor << endl;
cout << "Assign one object to another:\n";
StringBad knot;
knot = headline1;
cout << "knot: " << knot << endl;
cout << "Exiting the block.\n";
cout << "End of main()\n";
return 0;
}
void callme1(StringBad & rsb)
{
cout << "String passed by reference:\n";
cout << " \"" << rsb << "\"\n";
}
void callme1(StringBad & sb)
{
cout << "String passed by value:\n";
cout << " \"" << sb << "\"\n";
}
改進後的String類(添加了複製建構函式及賦值運算子)
12.4 string1.h
//string1.h -- fixed and augmented string class definition
#ifndef STRING1_H_
#define STRING1_H_
#include <iostream>
using namespace std;
class String
{
private:
char * str;
int len;
static int num_strings;
static const int CINLIM = 80;
public:
String(const char * s);
String();
String(const String &);
~String();
int length() const { return len };
//overloaded operator methods
String & operator=(const String &);
String & operator=(const char *);
char & operator[](int i);
const char & operator[](int i) const;
//overloaded operator friends
friend bool operator<(const String &st, const String &st2);
friend bool operator>(const String &st, const String &st2);
friend bool operator==(const String &st, const String &st2);
friend ostream & operator << (ostream & os, const String &st);
friend istream & operator >> (istream & is, String & st);
//static function
static int HowMany();
};
#endif //STRING1_H_
12.5 string1.cpp
//string1.cpp -- String class methods
#include <cstring>
#include "string1.h"
using namespace std;
int String::num_strings = 0;
int String::HowMany()
{
return num_strings;
}
String::String(const char * s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
num_strings++;
}
String::String()
{
len = 4;
str = new char[1];
str[0] = '\0';
num_strings++;
}
String::String(const String & st)
{
num_strings++;
len = st.len;
str = new char[len + 1];
strcpy(str, st.str);
}
String::~String()
{
--num_strings;
delete[]str;
}
String & String::operator=(const String & st)
{
if (this == &st)
return *this;
delete[]str;
len = st.len;
str = new char[len + 1];
strcpy(str, st.str);
return *this;
}
String & String::operator=(const char * s)
{
delete[]str;
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
return *this;
}
char & String::operator[](int i)
{
return str[i];
}
const char & String::operator[](int i) const
{
return str[i];
}
bool operator<(const String &st1, const String &st2)
{
return (strcmp(st1.str, st2.str) < 0);
}
bool operator>(const String &st1, const String &st2)
{
return st2 < st1;
}
bool operator==(const String &st1, const String &st2)
{
return (strcmp(st1.str, st2.str) == 0);
}
ostream & operator<<(ostream & os, const String & st)
{
os << st.str;
return os;
}
istream & operator>>(istream & is, String & st)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if (is)
st = temp;
while (is && is.get() != '\n')
continue;
return is;
}
12.6 sayings1.cpp
//sayings1.cpp -- using expanded String class
//compile with string1.cpp
#include <iostream>
#include "string1.h"
const int ArSize = 10;
const int MaxLen = 81;
int main()
{
using namespace std;
String name;
cout << "Hi, what's your name?\n>> ";
cin >> name;
cout << name << ", please enter up to " << ArSize << " short saying <empty line to quit>:\n";
String sayings[ArSize];
char temp[MaxLen];
int i;
for (i = 0; i < ArSize; i++)
{
cout << i + 1 << ": ";
cin.get(temp, MaxLen);
while (cin && cin.get() != '\n')
continue;
if (!cin || temp[0] == '\0')
break;
else
sayings[i] = temp;
}
int total = i;
if (total > 0)
{
cout << "Here are your sayings:\n";
for (i = 0; i < total; i++)
cout << sayings[i][0] << ": " << sayings[i] << endl;
int shortest = 0;
int first = 0;
for (i = 1; i < total; i++)
{
if (sayings[i].length() < sayings[shortest].length())
shortest = i;
if (sayings[i] < sayings[first])
first = i;
}
cout << "Shortest saying:\n" << sayings[shortest] << endl;
cout << "First alphabetically:\n" << sayings[first] << endl;
cout << "This program used " << String::HowMany() << " String objects. Bye.\n";
}
else
cout << "No input! Bye.\n";
return 0;
}
12.7 sayings2.cpp 使用指標追蹤新物件
//sayings2.cpp -- using pointers to objects
//compile with string1.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "string1.h"
const int ArSize = 10;
const int MaxLen = 81;
int main()
{
using namespace std;
String name;
cout << "Hi, what's your name?\n>> ";
cin >> name;
cout << name << ", please enter up to " << ArSize << " short saying <empty line to quit>:\n";
String sayings[ArSize];
char temp[MaxLen];
int i;
for (i = 0; i < ArSize; i++)
{
cout << i + 1 << ": ";
cin.get(temp, MaxLen);
while (cin && cin.get() != '\n')
continue;
if (!cin || temp[0] == '\0')
break;
else
sayings[i] = temp;
}
int total = i;
if (total > 0)
{
cout << "Here are your sayings:\n";
for (i = 0; i < total; i++)
cout << sayings[i] << endl;
String * shortest = &sayings[0];
String * first = &sayings[0];
for (i = 1; i < total; i++)
{
if (sayings[i].length() < shortest->length())
shortest = &sayings[i];
if (sayings[i] < *first)
first = &sayings[i];
}
cout << "Shortest saying:\n" << *shortest << endl;
cout << "First alphabetically:\n" << *first << endl;
srand(time(0));
int choice = rand() % total;
String * favorite = new String(sayings[choice]);
cout << "My favorite saying:\n" << *favorite << endl;
delete favorite;
}
else
cout << "Not much to say, eh?\n";
cout << "Bye.\n";
return 0;
}
再談定位new運算子
12.8 placenew1.cpp 定位new運算子
//placenew1.cpp -- new, placement new, no delete
#include <iostream>
#include <string>
#include <new>
using namespace std;
const int BUF = 512;
class JustTesting
{
private:
string words;
int number;
public:
JustTesting(const string & s = "Just Testing", int n = 0)
{
words = s;
number = n;
cout << words << " constructed\n";
}
~JustTesting()
{
cout << words << " destroyed\n";
}
void Show() const
{
cout << words << ", " << number << endl;
}
};
int main()
{
char * buffer = new char[BUF];
JustTesting *pc1, *pc2;
pc1 = new (buffer) JustTesting;
pc2 = new JustTesting("Heap1", 20);
cout << "Memory block address:\n" << "buffer: " << (void *)buffer << " heap: " << pc2 << endl;
cout << "Memory contents: \n";
cout << pc1 << ": ";
pc1->Show();
cout << pc2 << ": ";
pc2->Show();
JustTesting *pc3, *pc4;
pc3 = new(buffer) JustTesting("Bad Idea", 6);
pc4 = new JustTesting("Heap2", 10);
cout << "Memory contents:\n";
cout << pc3 << ": ";
pc3->Show();
cout << pc4 << ": ";
pc4->Show();
delete pc2;
delete pc4;
delete[] buffer;
cout << "Done\n";
return 0;
}
12.9 placenew2.cpp 加入了合適的delete和顯式解構函式
//placenew2.cpp -- new, placement new, no delete
#include <iostream>
#include <string>
#include <new>
using namespace std;
const int BUF = 512;
class JustTesting
{
private:
string words;
int number;
public:
JustTesting(const string & s = "Just Testing", int n = 0)
{
words = s;
number = n;
cout << words << " constructed\n";
}
~JustTesting()
{
cout << words << " destroyed\n";
}
void Show() const
{
cout << words << ", " << number << endl;
}
};
int main()
{
char * buffer = new char[BUF];
JustTesting *pc1, *pc2;
pc1 = new (buffer) JustTesting;
pc2 = new JustTesting("Heap1", 20);
cout << "Memory block address:\n" << "buffer: " << (void *)buffer << " heap: " << pc2 << endl;
cout << "Memory contents: \n";
cout << pc1 << ": ";
pc1->Show();
cout << pc2 << ": ";
pc2->Show();
JustTesting *pc3, *pc4;
pc3 = new(buffer + sizeof(JustTesting)) JustTesting("Better Idea", 6);
pc4 = new JustTesting("Heap2", 10);
cout << "Memory contents:\n";
cout << pc3 << ": ";
pc3->Show();
cout << pc4 << ": ";
pc4->Show();
delete pc2;
delete pc4;
pc3->~JustTesting();
pc1->~JustTesting();
delete[] buffer;
cout << "Done\n";
return 0;
}
複習:模擬佇列
12.10 queue.h
//queue.h -- interface for a queue
#ifndef QUEUE_H_
#define QUEUE_H_
class Customer
{
private:
long arrive;
int processtime;
public:
Customer(){ arrive = processtime = 0; }
void set(long when);
long when() const { return arrive; }
int ptime() const { return processtime; }
};
typedef Customer Item;
class Queue
{
private:
struct Node { Item item; struct Node * next; };
enum { Q_SIZE = 10 };
Node * front;
Node * rear;
int items;
const int qsize;
Queue(const Queue & q) : qsize(0) {}
Queue & operator=(const Queue & q) { return *this; }
public:
Queue(int qs = Q_SIZE);
~Queue();
bool isempty() const;
bool isfull() const;
int queuecount() const;
bool enqueue(const Item &item);
bool dequeue(Item &item);
};
#endif // !QUEUE_H_
12.11 queue.cpp
//queue.cpp -- Queue and Customer methods
#include "queue.h"
#include <cstdlib>
Queue::Queue(int qs /* = Q_SIZE */) :qsize(qs)
{
front = rear = NULL;
items = 0;
}
Queue::~Queue()
{
Node * temp;
while (front != NULL)
{
temp = front;
front = front->next;
delete temp;
}
}
bool Queue::isempty() const
{
return items == 0;
}
bool Queue::isfull() const
{
return items == qsize;
}
int Queue::queuecount() const
{
return items;
}
bool Queue::enqueue(const Item &item)
{
if (isfull())
return false;
Node * add = new Node;
add->item = item;
add->next = NULL;
items++;
if (front == NULL)
front = add;
else
rear->next = add;
rear = add;
return true;
}
bool Queue::dequeue(Item &item)
{
if (front == NULL)
return false;
item = front->item;
items--;
Node * temp = front;
front = front->next;
delete temp;
if (items == 0)
rear = NULL;
return true;
}
void Customer::set(long when)
{
processtime = std::rand() % 3 + 1;
arrive = when;
}
12.12 bank.cpp
//bank.cpp -- using the Queue interface
//compile with queue.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main()
{
using namespace std;
srand(time(0));
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs;
cin >> qs;
Queue line(qs);
cout << "Enter the number of simulation hours: ";
int hours;
cin >> hours;
long cyclelimit = MIN_PER_HR * hours;
cout << "Enter the average number of customers per hour: ";
double perhour;
cin >> perhour;
double min_per_cust;
min_per_cust = MIN_PER_HR / perhour;
Item temp;
long turnaways = 0;
long customers = 0;
long served = 0;
long sum_line = 0;
int wait_time = 0;
long line_wait = 0;
for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust))
{
if (line.isfull())
turnaways++;
else
{
customers++;
temp.set(cycle);
line.enqueue(temp);
}
}
if (wait_time < = 0 && !line.isempty())
{
line.dequeue(temp);
wait_time = temp.ptime();
line_wait += cycle - temp.when();
served++;
}
if (wait_time > 0)
wait_time--;
sum_line += line.queuecount();
}
if (customers > 0)
{
cout << "customers accepted: " << customers << endl;
cout << " customers served: " << served << endl;
cout << " turnaways: " << turnaways << endl;
cout << "average queue size: ";
cout.precision(2);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << (double)sum_line / cyclelimit << endl;
cout << "averahe wait time: " << (double)line_wait / served << " minutes\n";
}
else
cout << "No customers!\n";
cout << "Done!\n";
return 0;
}
bool newcustomer(double x)
{
return(rand()*x / RAND_MAX < 1);
}