C++ Namespace命名空間和static的用法總結

Namespaces are used to prevent name conflicts.

Ways to Use Namespace Identifiers

  1. use a qualified name consisting of the namespace, the scope resolution operator :: and the desired the identifier
    std::cin >> a
  2. write a using declaration
    using std::abs;
    cin >> a;
  3. write a using directive locally or globally
    using namespace std;
    cin >> a

例題
We need two counters.
Counter1 is a class and counter2 is an integer.
In counter1.h, you should complete the class counter1 by using static and overload the operator ()
In counter2.h, there should be an integer counter and two functions, set and count.
Read main.cpp to know more about the counter.
main.cpp

#include<iostream>
#include"counter1.h"
#include"counter2.h"
using namespace std;
int main() {
    counter2::set(3);
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        counter1::count();
    }
    for (int i = 0; i < m; i++) {
        counter2::count();
    }
    counter1 x;
    x();
    cout << counter1::counter << endl;
    cout << counter2::counter << endl;
}

counter.1cpp

#ifndef COUNTER1_H
#define COUNTER1_H
class counter1 {
    public:
        void operator()() {
            ++counter;
        }
        void count() {
            ++counter;
        }
        static void set(int x) {
            counter = x;
        }
        static int counter;
};
int counter1::counter = 0;
#endif   

counter2.cpp

#ifndef COUNTER2_H
#define COUNTER2_H
namespace counter {
    int counter = 0;
    void count() {
        counrt++;
    }
    void set(int x) {
        counter = x;
    }
};
#endif

關於static的用法
靜態數據成員
被當作類的成員,不管該類被定義多少次,其拷貝只有一份,所有對象共享,且不在類聲明中定義

class name {
    static int sum;
    ....
}
int name::sum = 0;

靜態成員函數
也屬於這個類,不具有this指針,且無法訪問屬於類對象的非靜態成員和函數

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