6.3隨筆(類中的友元以及靜態)

今天摸魚時間不算長,期末了,作業什麼的比較多

C++友元函數以及友元類

友元函數

先直接給出性質:

  • 類的友元函數定義在類外部,但有權訪問類的所有私有(private)成員和保護(protected)成員。
  • 儘管友元函數的原型有在類的定義中出現過,但是友元函數並不是成員函數。
  • 如果要聲明函數爲一個類的友元函數,需要在類定義中該函數原型前使用關鍵字 friend

下面是一個簡單的例子:

#include <iostream>
using namespace std;

class person
{
public:
    int score = 100;
    void print();
    friend void print2(person temp); //使用關鍵字friend
private:
    string name = "hesorchen";
};
void person::print() //成員函數
{
    cout << name << ' ' << score << endl;
}
void print2(person temp) //友元函數
{
    cout << temp.name << ' ' << temp.score << endl;
}

int main()
{
    person a;
    a.print(); //成員函數
    print2(a); //友元函數
    return 0;
}

友元類

一個類 A 可以將另一個類 B 聲明爲自己的友元,類 B 的所有成員函數就都可以訪問類 A 對象的私有成員。在類定義中聲明友元類的寫法如下:

friend  class  類名;

例子:

#include <iostream>
using namespace std;

class person
{
public:
    int score = 100;
    void print();
    friend void print2(person temp); //使用關鍵字friend
    friend class dog;

private:
    string name = "hesorchen";
};
void person::print() //成員函數
{
    cout << name << ' ' << score << endl;
}
void print2(person temp) //友元函數
{
    cout << temp.name << ' ' << temp.score << endl;
}

class dog //友元類
{
public:
    int age;
    void print(person a)
    {
        cout << "Owner is:" << a.name << endl; //可以訪問person類的private成員變量name
    }

private:
    string name;
};
int main()
{
    person a;
    dog b;
    a.print(); //成員函數
    print2(a); //友元函數
    b.print(a);

    return 0;
}

先來簡單說一下static修飾的靜態變量

static修飾的變量,僅在第一次執行該語句時初始化,之後不再初始化。他的內存被分配在全局數據區中,但是作用域在局部作用域。

靜態數據成員以及靜態成員函數

靜態數據成員

類的靜態數據成員比較複雜,總結幾點比較重要的性質吧
1.靜態數據成員在類中只能聲明不能定義,要對其進行定義只能在全局作用域中定義
2.靜態數據成員不屬於任何對象,它被類的所有對象共享,包括派生類

示例1
class person
{
public:
    string name;
    int age;
    static int score; //聲明
};
int person::score = 1; //定義
/*
int Class::a=10;
數據類型+類名+作用域符號+變量名=10;
*/
示例2
#include <iostream>
using namespace std;

class person
{
public:
    string name;
    int age;
    static int score; //聲明
};
int person::score = 1; //定義
class teacher : public person
{
};

int main()
{
    person a, b;
    teacher c;
    cout << teacher::score << endl;
    cout << a.score << ' ' << b.score << ' ' << c.score << endl;
    a.score++;
    cout << a.score << ' ' << b.score << ' ' << c.score << endl;
/*
Output:
1
1 1 1
2 2 2
*/
    return 0;
}

靜態成員函數

與靜態數據成員相類似地有:
1.定義方式相似
2.屬於類而不屬於對象
3.靜態成員函數不屬於某個對象,自然也就不存在this指針

示例:

#include <iostream>
using namespace std;

class person
{
public:
    string name;
    int age;
    static void print(); //聲明
};
void person::print() //定義
{
    cout << "hello world!" << endl;
}

int main()
{
    person::print();
    person a;
    a.print();
    return 0;
}   

今天個人覺得還算充實,不過還是有任務拖欠到了明天,而且沒早睡… …

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