Namespaces are used to prevent name conflicts.
Ways to Use Namespace Identifiers
- use a qualified name consisting of the namespace, the scope resolution operator :: and the desired the identifier
std::cin >> a
- write a using declaration
using std::abs;
cin >> a; - 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指针,且无法访问属于类对象的非静态成员和函数