Happy劍指offer:第2章題目筆記

來源:互聯網
上載者:User

標籤:

判斷題1

涉及到的一個問題是類內賦值建構函式的傳值問題。如果允許複製建構函式傳值,就會在賦值建構函式內部遞迴一般的進行對複製建構函式的調用,最終必然導致棧溢出。

如果仔細觀察就會發現,如果要是調用複製建構函式,賦值建構函式的輸入參數必然是引用形式。

舉例;

A(const A &other)

面試題1

自己在定義一個類的時候,對建構函式,仍然會有一點點的不確定。

嘗試了一把運算子多載。感覺還好,注意的是

1. 輸入為引用,輸出為引用

2. 對於指標,注意分配記憶體和釋放記憶體。

//offer1class CMyString{public:    CMyString(char* pData = NULL);//這個應該只能算是聲明吧    CMyString(const CMyString& str);    ~CMyString(void);    CMyString& operator =(const CMyString &str);private:    char* m_pData;};CMyString& CMyString::operator = (const CMyString &str){    if (this == &str)        return *this;    delete[]m_pData;    m_pData == NULL;    m_pData = new char[strlen(str.m_pData) + 1];    strcpy(m_pData, str.m_pData);        return *this;}
面試題2

singleton模式:即單例模式。數學與邏輯學中,singleton定義為“有且僅有一個元素的集合”

如果一個類和singleton模式相關聯,那麼毫無疑問,這是一個特殊類,因為這種類只有一個對象,所以稱為單例,單個例子嘛。一般這種單例非常容易被外界訪問。

優點:節約系統資源。

產生執行個體的方法是靜態方法。

//offer2 實現singleton模式class Singleton{public:    static Singleton& GetInstance()    {        static Singleton Instance;        return Instance;    }private:    Singleton();    Singleton(const Singleton& other);    ~Singleton();    Singleton& operator=(const Singleton& other);};
面試題3

注意int* matrix只能是代表一維數組。思路知道之後這道題突然間變得好簡單。

//offer3bool Find(int* matrix, int rows, int columns, int number){    bool IsFound = false;    if (matrix != NULL && rows > 0 && columns > 0)    {        int row = rows-1;        int column = 0;        while (row >= 0 && column < columns)        {            if (matrix[row*columns + column] == number)            {                IsFound = true;                break;            }            else            {                if (matrix[row*columns + column] < number)                {                    ++column;                }                else                {                    --row;                }            }        }    }    return IsFound;}

判斷題2:

兩個字串均定義為char str[]類型的時候,判斷兩個字串是否相等,需要判定兩個是不是指向相同的記憶體空間。這個問題十分重要。並非內容一樣就可以的。另一種:char* str就不存在這個問題。它們定義的時候會自動指向對應的記憶體位址的。

Happy劍指offer:第2章題目筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.