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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值