C++ Namespace命名空间和static的用法总结

来源:互联网 发布:sql重命名列名 编辑:程序博客网 时间:2024/06/06 15:26

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_Hclass 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_Hnamespace 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指针,且无法访问属于类对象的非静态成员和函数

0 0
原创粉丝点击