浙大 C++ 课程学习笔记3 - 关键字const

71 阅读2分钟

浙大 C++

网易云课堂-C++

const

  1. const

declares a variable to have a contant value.

const int x = 1; // 
x = 2; // illegal
x++; // illegal

int y = x; // ok, copy const to non-const
y = x; // ok, same thing
const z = x; // ok, const is safer
  1. Constants (被 const 关键字修饰的变量)
  • Constants are variables
  • Oberve scoping rules
  • Declared with "const" type modifier
  1. Compile time constants
  • const int bufsize = 1024;
    • value must be initialized
    • unless you make an explicit extern declaration
  • extern const int bufsize;
    • Compiler won't let you change it

Compile time constants are entries in compiler symbol table, not really variables.

  1. runtime constants

const value can be exploited

const int size = 10;
int arr[size];  // ok

int x;
cin >> x;
const int size_a = x;
int arr_a[size_a];  // error
  1. pointers and const
char * const q = "abc"; // point is const
*q = 'c'; // 指针不能修改,但指针里的值依然可以修改
q++; // error

const char *p = "abc"; // (*p) is a const char
*p = 'c'; // error
p++; // ok
  1. what do these mean?
Person person;
const Person* p1 = &person; // obj is const
Person const* p2 = &person; // obj is const
Person *const p3 = &person; // point is const

const 写在 * 号之前表示 对象是 const 的,写在 * 号后面表示 指针是 const 的。

const Person *const p4 =  &person; // obj and point is const
  1. pointers and constants

image.png

  1. string literals

image.png

char *s = "hello"; // 放到代码段里,作为常量不能修改
s[0] = 'a'; // Bus error

char s2[] = "hello";  // 数组是放在堆栈里,可以修改
s2[0] = 'a';
  1. Converions

Can always treat a non-const value as const

void f(const int* x);
int a = 15;
f(&a);

const int b = a;

f(&b);
b = a + 1;// error

You cannot treat a constant object as non-constant without an explicit cast(const_cast);

  1. Passing by const value?
void f(const int x){
    x++; // compile-time error
}
  1. Returning by const value?
int f3(){return 1;}
const int f4(){return 1;}
int main(){
    const int x = f3(); // ok
    int y = f4(); // ok
}

image.png

  1. constant objects
const Person p("mcc", 30); // 对象和对象的值都不能修改
// 但是方法可能会出问题
  1. const member functions

image.png

不可修改的对象

class A{
    int i;
public:
    A() : i(0){}
    // f() 可以重载
    void f(){ cout << "A::f()";}                // void f(A* this){}
    void f() const { cout << "A::f() const";}   // void f(const A* this){}
    
}

int main(){
    const A a;
    a.f(); // A::f() const
    return 0;
}
  1. constant in class
class A{
    const int i;
}

has to be initialized in initializer list of the construtor.

  1. compile-time constants in classes
class A{
    const int size;
    int array[size]; //error
}

class B{
    static const int size = 100;
    int array[size]; //ok
}

class C{
    enum {size = 100};
    int array[size]; // ok
}