- #include <iostream>
- class A
- {
- public:
- A()
- {
- this->i = 1;
- }
- int get() const
- {
- return this->i;
- };
- void set(int i)
- {
- this->i = i;
- };
- private:
- int i;
- };
- int main()
- {
- // 指针常量, 必须在声明时进行初始化。
- A *const p = new A;
- std::cout << p->get() << std::endl;
- p->set(3);
- // p = p + 1; 编译就报错了。
- std::cout << p->get() << std::endl;
- // 指向常量的指针
- const A *p1 = new A;
- std::cout << p1 << std::endl;
- p1 = p1 + 1;
- // p1->set(3); 编译就报错了。
- std::cout << p1 << std::endl;
- // 指向常量的常指针
- const A *const p2 = new A;
- std::cout << p2->get() << std::endl;
- return 0;
- }
总结:const修饰的是什么,什么就是常量