C++笔记 - const

206 阅读2分钟

const 是类型修饰符,通常用于修饰不可变变量

  • 用于定义常量。如:const int num = 100;定义常量一般也会使用#define进行定义,但使用const的好处是,编译器会进行类型检查,而使用#define则不会。

  • 使用const修饰的默认为文件局部变量, 即如果需要跨文件访问变量,需要使用extern进行初始化修饰,如:extern int num = 100; 才能从另外一个文件进行访问。而没有使用const修饰的变量默认是extern的,不需要显式的使用extern修饰。

  • const常量必须初始化。如:

    #include <iostream>
    
    class num {
        public:
            const int a = 100;
    
        public:
            void print() const;
    };
    
    void num::print() const {
        std::cout << "a: " << this->a << std::endl;
    }
    
    int main(void) {
        auto n = num{};
        std::cout << n.a << std::endl;
        n.print();
    }
    
  • const 与指针:

    const char *str = "hello";
    char *const str = "hello";
    

    const* 左边时,不能通过*str = "world;"进行赋值, 即*str是不可变的。当const*右边时, 不能通过str = nullptr;进行赋值, 即str是不可变得。

  • 可以将const的指针赋值给const的指针;反之不行。

    int num = 10;
    const int *const_num = &num;
    
  • 在函数参数中使用const,可限制函数对参数的使用。

    void copy(char *dst, const char *src);
    

    通过对src参数使用const修饰,要求copy函数实现是不能通过src变量修改源字符串的内容,否则编译器会报错。

  • 在类中初始化const成员。

    #include <iostream>
    
    class num {
        public:
            const int a;
    
        public:
            void print() const;
            num(int a);
    };
    
    num::num(int a): a(a) { }
    
    void num::print() const {
        std::cout << "a: " << this->a << std::endl;
    }
    
    int main(void) {
        auto n = num{100};
        std::cout << n.a << std::endl;
        n.print();
    }
    
  • 使用static修饰const变量时,可以在类内/外部进行初始化。

    class num {
        public:
            static const int b;
            static const int c = 100;
    };
    
    const int num::b = 100;
    

上面是对const用法的一点总结,发现有新的用法会持续补充。