C++ 類中const成員變量的賦值

在頭文件的類的定義中定義了一個const成員變量

C++ 規則:
1、類定義中不能進行初始化,因爲頭文件中類的定義只是一個聲明,並沒有分配真正空間,因此變量是不存在的,因此是不能賦值的。
2、const 定義的變量是不能賦值
這可如何是好,聲明中不能賦值,聲明完還不能賦值。又不能不賦值。
解決方案:
1、在構造函數後的參數初始化列表中初始化
2、將const變量同時聲明爲 static 類型進行初始化。

 

#include <iostream>

class TestA
{

public:

    TestA(): m_iSIZE(20) {}    // method 1
    ~TestA(){}

    int GetSize()

    {
        return m_iSIZE;
    }

private:
    const int m_iSIZE;
};

class TestB
{
public:
    TestB(){}

    ~TestB(){}

    int GetSize()
    {
        return m_iSIZE;
    }

private:
    static const int m_iSIZE;
};
const int TestB::m_iSIZE = 3;    // method 2
int main()
{
    TestA oTestA;
    TestB oTestB;

    std::cout << "oTestA:" << oTestA.GetSize() << std::endl;

    std::cout << "oTestB:" << oTestB.GetSize() << std::endl;
    return 0;
}

 

出處:http://apps.hi.baidu.com/share/detail/33986387

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章