2010-03-14 40 views
1

何時應該內聯一個成員函數,什麼時候應該使用成員初始值設定項?內聯和成員初始值設定項

我的代碼如下..我想修改它,所以我可以利用一些內嵌在適當的時候和成員初始化:

#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(); 
} 
} 
+1

'strdup()'在一個C++類中?當然你會開玩笑。 (你忘了'免費()') – 2010-03-14 19:15:42

回答

3

短的成員函數調用經常是內聯很好的候選人。爲了使成員函數「ininable」,你需要在頭文件中定義它(無論是在類定義本身,還是在使用關鍵字inline的類定義下面)。

你應該總是使用構造函數初始化列表來初始化成員數據。對於用戶定義的類型,這可能會在某些情況下產生顯着的性能差異。你的構造應該是這樣的:

Book::Book() : nm(""), thck(0), wght(0) { } 

Here就是爲什麼要使用初始化列表一個很好的解釋。

1

簡短的回答 - 不是從一開始。爲頭文件中的類聲明清理接口,並首先將所有實現細節放入.cpp文件中。測量,剖析,並從那裏開始。

至於初始化程序 - 使用它們總是。編譯器無論如何都會爲你做這件事,所以在構造函數體中分配數據成員是多餘的(對於類類型成員可能會很昂貴)。當需要顯式地完成工作時,只有少數情況會出現成員變量依賴和較低級別的C調用在構造函數體中。

+0

「編譯器爲你做了它......」小心解釋一下嗎? – 2010-03-14 19:40:11

+0

@STingRaySC:編譯器在構造函數的主體之前插入代碼,以默認方式初始化所有基類(爲了在class X之後出現)和成員變量(爲了聲明順序)。相反的情況發生在*析構函數的主體之後 - 編譯器插入代碼來調用成員的析構函數,順序相反,然後是基本析構函數。 – 2010-03-14 21:03:11

+0

只有用戶定義類型的成員變量是默認初始化的。這正是使構造函數體中的賦值相對於初始化器列表中的初始化效率降低的原因。對於內置類型的成員數據,成員不是由編譯器初始化的,因此在構造函數體中爲它們分配* not *冗餘。從技術上講,即使對於UDT,沒有任何東西是多餘的,因爲它的默認構造函數將被調用,後面是構造函數體中的賦值運算符。 – 2010-03-14 22:04:19

相關問題