浙大 C++
const
- 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
- Constants (被 const 关键字修饰的变量)
- Constants are variables
- Oberve scoping rules
- Declared with "const" type modifier
- 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.
- 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
- 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
- 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
- pointers and constants
- string literals
char *s = "hello"; // 放到代码段里,作为常量不能修改
s[0] = 'a'; // Bus error
char s2[] = "hello"; // 数组是放在堆栈里,可以修改
s2[0] = 'a';
- 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);
- Passing by const value?
void f(const int x){
x++; // compile-time error
}
- Returning by const value?
int f3(){return 1;}
const int f4(){return 1;}
int main(){
const int x = f3(); // ok
int y = f4(); // ok
}
- constant objects
const Person p("mcc", 30); // 对象和对象的值都不能修改
// 但是方法可能会出问题
- const member functions
不可修改的对象
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;
}
- constant in class
class A{
const int i;
}
has to be initialized in initializer list of the construtor.
- 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
}