static
文件域+位置域(局部,类)
在一个类中声明了,在类外定义,static变量定义时所在的文件,就构成了该变量的作用范围。
一个类的static变量,如果在头文件中定义,
多个其他文件include这个文件的时候,就会使得这个static有多个实体。
也就是一个类定义了多个static变量,然后就会报错!
因为这个变量的作用域是由文件,类两者确定的,通过文件那一关,却没有通过类那一关。
所以类的static变量一般在类的定义文件cpp中定义,即初始化。
t.h
#ifndef _ZJJTT_
#define _ZJJTT_
#include <stdio.h>
/*
one include one instance!
*/
static int mStatic = 0;
class A {
public:
/*
c.o:(.bss+0x0): multiple definition of `A::mClass'
b.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
static int mClass;
*/
static void inFunc() {
static int mStatic;
printf("inFunc:%08x\n", &mStatic);
}
};
/*
Therefore definition should be in the cpp file
int A::mClass;
*/
/*
c.o:(.bss+0x0): multiple definition of `mGlobal'
b.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
int mGlobal;
*/
void foo();
#endif
#include "t.h"
#include <stdio.h>
int main() {
printf("b.cpp:%08x\n", &mStatic);
foo();
A::inFunc();
}
#include "t.h"
#include <stdio.h>
void foo() {
printf("c.cpp:%08x\n", &mStatic);
A::inFunc();
}
b.o: b.cpp c.o: c.cpp all: b.o c.o g++ $^ -o a.out clean: rm *.o a.out -rf
运行结果
b.cpp:00600a54
c.cpp:00600a5c
inFunc:00600a58
inFunc:00600a58
const
const type * const fun(const type * const) const { }
这个情况也够多的,我们来看看每个的用法。
比较特别的是后面的const,作用在成员函数时,表示不可改变类中成员变量。
class Foo {
public:
int val;
void fun() const {
//val = 0;//wrong
}
};
type * const ptr; //ptr的值不可改变
const type * ptr; //ptr指向的内容不可改变
type * const 一般不作为返回值的类型,因为它可以说跟直接type * 的效果是一样的。
当const作用在非指针的类型上时,type const 和const type是一回事。
const type一般不作为函数返回值的,因为没意义。但是const type &就比较多用在返回值了,
例如复制函数(==)等。
static const和const static作用的最后效果是一样的。
在类中,类外定义都可以。除了有常量性质外其他跟static一样。
在不同编译器可能对于它们的处理过程可能不一样。