何時應該內聯一個成員函數,什麼時候應該使用成員初始值設定項?內聯和成員初始值設定項
我的代碼如下..我想修改它,所以我可以利用一些內嵌在適當的時候和成員初始化:
#include "Books.h"
Book::Book(){
nm = (char*)"";
thck = 0;
wght = 0;
}
Book::Book(const char *name, int thickness, int weight){
nm = strdup(name);
thck = thickness;
wght = weight;
}
Book::~Book(){
}
const char* Book::name(){
return nm;
}
int Book::thickness(){
return thck;
}
int Book::weight(){
return wght;
}
//
// Prints information about the book using this format:
// "%s (%d mm, %d dg)\n"
//
void Book::print(){
printf("%s (%d mm, %d dg)\n", nm, thck, wght);
}
Bookcase::Bookcase(int id){
my_id = id;
no_shelf = 0;
}
int Bookcase::id(){
return my_id;
}
Bookcase::~Bookcase(){
for (int i = 0; i < no_shelf; i++)
delete my_shelf[i];
}
bool Bookcase::addShelf(int width, int capacity){
if(no_shelf == 10)
return false;
else{
my_shelf[no_shelf] = new Shelf(width, capacity);
no_shelf++;
return true;
}
}
bool Bookcase::add(Book *bp){
int index = -1;
int temp_space = -1;
for (int i = 0; i < no_shelf; i++){
if (bp->weight() + my_shelf[i]->curCapacity() <= my_shelf[i]->capacity()){
if (bp->thickness() + my_shelf[i]->curWidth() <= my_shelf[i]->width() && temp_space < (my_shelf[i]->width() - my_shelf[i]->curWidth())){
temp_space = (my_shelf[i]->width()- my_shelf[i]->curWidth());
index = i;
}
}
}
if (index != -1){
my_shelf[index]->add(bp);
return true;
}else
return false;
}
void Bookcase::print(){
printf("Bookcase #%d\n", my_id);
for (int i = 0; i < no_shelf; i++){
printf("--- Shelf (%d mm, %d dg) ---\n", my_shelf[i]->width(), my_shelf[i]->capacity());
my_shelf[i]->print();
}
}
'strdup()'在一個C++類中?當然你會開玩笑。 (你忘了'免費()') – 2010-03-14 19:15:42