c++第三次做業

const & static

靜態成員 (static)

1.靜態生存期
對象的生存期與程序的運行期相同,則稱它具備靜態生存期。
[細節]定義時未指定初值的基本類型靜態生存期變量,會被賦予0來初始化,而動態生存期變量不指定初值意味着初值時隨機數。
ios

2.靜態變量特色
不隨每次函數調用產生一個副本,也不隨函數返回而失效,實現數據共享。函數

3.舉例子引出問題
關於一個公司有多少人員的問題,若是問公司的A和B,他們說的答案應該是同樣的,但是要怎麼用代碼來實現這種數據的一致性呢,這就須要用到靜態成員。測試

#include<iostream>
using namespace std;
class Point
{
public:
    Point(int x = 0, int y = 0) :x(x), y(y)
    {
        count++;
    }
    Point(Point &p)
    {
        x = p.x;
        y = p.y;
        count++;
    }
    ~Point()
    {
        count--;
    }
    int getX() { return x; }
    int getY() { return y; }
    void showCount()
    {
        cout << "   Object count is " << count << endl;
    }
private:
    int x, y;
    static int count;//靜態數據成員變量
};
int Point::count = 0;
//靜態數據成員定義和初始化用類名限定,它在對象被建立以前就已經存在,因此不用構造函數來初始化
int main()
{
    Point a(4, 5);//構造函數被調用count=1
    cout << "Point A: " << a.getX() << ";" << a.getY();
    a.showCount();
    Point b(a);//複製構造函數被調用,count在原基礎上進行自加,count=2
    cout << "Point B:"<<b.getX() <<";"<<b.getY();
        b.showCount();
    return 0;
}

代碼結果

4.靜態函數成員
聲明:static 函數返回值類型 函數名(參數表) ;
靜態成員函數能夠直接訪問該類的靜態數據和函數成員,而訪問非靜態成員,必須經過對象名。
spa

calss A
{
    public:
    static void f(A a);
    private:
    int x;
};
void A::f(A a)
{
    cout<<x;//錯誤
    cout<<a.x;//正確
}

常對象(const)

1.定義
數據成員值在對象的整個生存週期內不能被改變。
常對象必須初始化,不能被更新code

const int n=1;
n=3;//錯,不能對常量賦值

2.常成員函數
聲明:類型說明符 函數名(參數表)const;
一個對象若爲常對象,則經過該對象只能調用它的常成員函數; 不管是否經過常對象調用常成員函數,在常成員函數調用期間,目的對象都被視爲常對象。
3.實例與測試
對象

#include<iostream>
using namespace std;
class R
{
public:
    R(int r1,int r2):r1(r1),r2(r2)
    {
    
    }
    void print();
    void print()const;//常成員函數
private:
    int r1, r2;
};
void R::print()
{
    cout << r1 << " ; " << r2<<endl;
}
void R::print()const//區別於上一個輸出函數
{
    cout << r1 << " ; " << r2;
    cout << "    function of const is calling" <<endl;
}
int main()
{
    R a(4, 5);
    a.print();
    const R b(20, 25);
    b.print();//調用常成員函數
    return 0;
}

代碼結果
blog

相關文章
相關標籤/搜索