C++ const

CONST:

 the C++ compiler avoids creating storage for a const, but instead holds the definition in its symbol table. When you use extern with const, however, you force storage to be allocated .

 const modified value cannot be used at compile time because the compiler is not required to know the contents of the storage at compile time.

实例:

const int i[] = { 1, 2, 3, 4 };

float f[i[3]]; // Illegal

Pointer to const : const int* u;

const pointer :int d = 1;  int* const w = &d;

 you can’t assign the address of a const object to a non-const pointer(虽然事实上这样做编译器不会报错,但是破坏了原本的意思,不是好的编程实践)

char* cp = "howdy";

is created by the compiler as a constant character array, Modifying any of the characters in the array is a runtime error, although not all compilers enforce this correctly.

 it’s possible to pass a temporary object to a function that takes a const reference, whereas you can never pass a temporary object to a function that takes a pointer – with a pointer, the address must be explicitly taken. So passing by reference produces a new situation that never occurs in C: a temporary, which is always const, can have its address passed to a function. This is why, to allow temporaries to be passed to functions by reference, the

argument must be a const reference. The following example demonstrates this:

class X {}; 

X f() { return X(); } // Return by value

void g1(X&) {} // Pass by non-const reference

void g2(const X&) {} // Pass by const reference

int main() {

  // Error: const temporary created by f():

//!  g1(f());

  // OK: g2 takes a const reference:

  g2(f());

} ///:~

 To guarantee the constness of a class object, the const member function is introduced: only a const member function may be called for a const object. (也就是说const object 只能调用 const 类型的成员函数,const member function 就是在参数列表后面加const 参数,下面将会有实例)

Thus, when you create an ordinary (non-static) const inside a class, you cannot give it an initial value. This initialization must occur in the constructor, of course, but in a special place in the constructor. Example:

#include <iostream>

using namespace std;

class Fred {

  const int size;

public:

  Fred(int sz);

  void print();

};

Fred::Fred(int sz) : size(sz) {}

void Fred::print() { cout << size << endl; }

int main() {

  Fred a(1), b(2), c(3);

  a.print(), b.print(), c.print();

}

Thus, a static const of a built-in type can be treated as a compile-time constant.

There is one feature of static const when used inside classes which is a bit unusual: you must provide the initializer at the point of definition of the static const.

class StringStack {

  static const int size = 100;//static const 需要在声明时初始化

  const string* stack[size];

  int index;

public:

  StringStack();

  void push(const string* s);

  const string* pop();

};

the syntax for declaring const member functions: place the const specifier after the argument list

 If you declare a member function const, you tell the compiler the function can be called for a const object. A member function that is not specifically declared const is treated as one that will modify data members(也就是说const成员函数不能修改数据成员!) in an object, and the compiler will not allow you to call it for a const object(也就是说const object 不能调用非const member fucntion).

Any function that doesn’t modify member data should be declared as const, so it can be used with const objects.

Void func(const Object &)  : 可以用来操作const 和非 const object

Object :: func() const;          : 可以被const object 调用 object.func()

上面两种情况没有const限制后面的调用方式都是不可以的!

如果你创建了一个const成员函数而用想改变该类中的数据成员该怎么办呢?

 You take this (the keyword that produces the address of the current object) and cast it

to a pointer to an object of the current type.

实例:

class Y {

  int i;

public:

  Y();

  void f() const;

};

Y::Y() { i = 0; }

void Y::f() const {

//!  i++; // Error -- const member function

  ((Y*)this)->i++; // OK: cast away const-ness

  // Better: use C++ explicit cast syntax:

  (const_cast<Y*>(this))->i++;

}

int main() {

  const Y yy;

  yy.f(); // Actually changes it!

}

另外一种方法:

 To put everything out in the open, you should use the mutable keyword in the class declaration to specify that a particular data member may be changed inside a const object

实例:

class Z {

  int i;

  mutable int j;

public:

  Z();

  void f() const;

};

Z::Z() : i(0), j(0) {}

void Z::f() const {

//! i++; // Error -- const member function

    j++; // OK: mutable

}

int main() {

  const Z zz;

  zz.f(); // Actually changes it!

说明:该内容来源于“think in C++”,之前学习过放在了oneNote 里面,现在再次拿来复习

这个也总结得很好:http://blog.csdn.net/Eric_Jo/article/details/4138548

原文地址:https://www.cnblogs.com/zhuyp1015/p/2562611.html