2010-07-15 43 views
3

我想了解STL中用於類的語法。我們的老師指着我們到這個網站(http://www.sgi.com/tech/stl/Map.html),我複製下面的代碼:在C++(STL)結構中聲明的方法

struct ltstr 
{ 
    bool operator()(const char* s1, const char* s2) const 
    { 
    return strcmp(s1, s2) < 0; 
    } 
}; 

int main() 
{ 
    map<const char*, int, ltstr> months; 

    months["january"] = 31; 
    months["february"] = 28; 
    months["march"] = 31; 
    months["april"] = 30; 
    months["may"] = 31; 
    months["june"] = 30; 
    months["july"] = 31; 
    months["august"] = 31; 
    months["september"] = 30; 
    months["october"] = 31; 
    months["november"] = 30; 
    months["december"] = 31; 

    cout << "june -> " << months["june"] << endl; 
    map<const char*, int, ltstr>::iterator cur = months.find("june"); 
    map<const char*, int, ltstr>::iterator prev = cur; 
    map<const char*, int, ltstr>::iterator next = cur;  
    ++next; 
    --prev; 
    cout << "Previous (in alphabetical order) is " << (*prev).first << endl; 
    cout << "Next (in alphabetical order) is " << (*next).first << endl; 
} 

我不知道你能在結構中聲明的方法。這是如何運作的?

我假設用它,當你聲明名爲月的地圖,使用地圖比較字段中的光澤alphabetizes地圖。但仍然不確定它如何與struct語法一起工作。謝謝。

在C++結構

回答

15

在C++中,一個struct實際上只是一個類,它的默認訪問說明符是public和默認公開繼承。

換句話說,

struct ltstr 
{ 
    // ... 
}; 

如果你願意,你可以讓你的結構protectedprivate的部分相當於

class ltstr 
{ 
public: 
    // ... 
}; 

了。

struct仍然在C++中,即使它是多餘的原因是向後兼容。

+4

繼承默認也是公開的,這就是爲什麼我使用這麼多結構... – 2010-07-15 13:36:36

+0

@Alexandre:好點 - 我已經將其納入答案。 – 2010-07-15 13:41:54

+0

@Alexandre:Oooops ...應該已經檢查過。這意味着這兩個代碼片段不僅幾乎相當,而且完全相同...... – 2010-07-15 13:53:33

1

是類公共成員默認

+3

您的意思是,默認情況下爲公共成員 – corsiKa 2010-07-15 13:35:46

+3

默認情況下爲公共繼承。 – oscode 2010-07-15 13:36:19

+0

@glowcoder:你說得對,對不起 – onof 2010-07-15 13:37:16

0

與公共成員上的默認值相比,該結構不會添加任何功能。因此,這些功能都不是結構特定的。