static和const的使用

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一样。

在不同编译器可能对于它们的处理过程可能不一样。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值