天天看點

《劍指offer》01 指派運算符函數

sizeof(一個空類)為什麼不是0?

答:空類型的執行個體不包含任何資訊,本應該是0,但是當我們聲明該類型的執行個體的時候,它必須在記憶體中占有一定的空間,否則無法使用這些執行個體。

調用構造函數和析構函數秩序要知道函數的位址,這些函數的位址隻與類型相關,而與類型的執行個體無關。

如果把析構函數标記為虛函數呢?

答:會生成虛函數表,并在該類型的每個執行個體中添加一個指向該虛函數表的指針。32位,4位元組 64位,8位元組。

class A
{
private:
           int value;
public:
          A( int n )
          {
                   value = n;
          }
           //A(A other)   //error  C++标準不允許複制構造函數傳遞參數
          A( const A & other)
          {
                   value = other.value;
          }
           void Print()
          {
                   cout << value << endl;
          }
};
int main()
{
           A a = 10;
           A b = a;
          b.Print();
          system( "pause");
           return 0;
}      

面試題1:指派運算符函數

初級程式員:

<pre name="code" class="cpp">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 ;
}      

進階程式員:要考慮異常安全性的解法。(指派運算符的現代寫法)

CMyString&  CMyString ::operator=(const CMyString &str )
{
           if (this != &str)
          {
                    CMyString strTemp(str );
                    char* pTemp = strTemp.m_pData;
                   strTemp.m_pData = m_pData;
                   m_pData = pTemp;
          }
          
           return *this ;
}