Person p1("fred", 20);
const Person *p = &p1; // 指针p指向的是const person类的对象,该对象不能修改,但指针可指向其他的person对象
Person const *p = &p1; // 和上面一致的意思,只是不同的写法
Person *const p = &p1; // p指针是一个const指针,指向Person对象,该指针只能指向p1, 不能指向其他对象,但p1对象可修改
区别的标准是 在*号的前面还是后面
在*号的前面 则对象是const
在*号的后面 则指针是const
也可以将指针和对象都变成const
const Person *const p = &p1;
cip 全称是他指向的变量不能通过他修改的指针
const int *cip;
int i ;
cip = &i; // 这是允许的
// i的值可以变化, 但是不能通过cip去修改i的值(即*cip = 54),尽管他们是同一个东西
字符串
#include<stdio.h>
int main(){
char *p = "hello world";
char arr[] ="hello world";
printf("p\t=%p\n",p);
printf("arr\t=%p\n",arr);
printf("main\t=%p\n",main);
return 0;
}
p =0x55fbc62d07d4
arr =0x7ffff25108dc
main =0x55fbc62d06aa一个在代码段 一个在栈里面
不可以修饰的对象
当使用const 修饰对象,那么其会修改对象变量值的函数将不可被调用
而标识有const的函数 则可以被调用
在函数的后面 标识 const (原型和定义的地方都需要重复)
表示这个函数不会修改对象。
int get_day() const;
int get_day() const {return day;}
const 在这本身的含义是说 this
是const
#include<iostream>
class A
{
private:
int i;
public:
A() : i(0){};
~A();
// 没有构成重复定义,构成了overload关系, 因为其参数表不同
void f() { std::cout << "f()" << std::endl;};
void f() const { std::cout << "f() const" << std::endl;}
// 等价于
void f(A *this) { std::cout << "f()" << std::endl;};
void f(const A *this) const { std::cout << "f() const" << std::endl;}
};
A::~A(){}
int main() {
const A a;
a.f();
return 0;
}
如果成员变量是const 那么需要在initialize-list 里被初始化,否则会报错
也可以在前面加上 static
#include<iostream>
class A{
private:
const int i;
public:
A() {};
~A();
void f() { std::cout << "f()" << std::endl;};
void f() const { std::cout << "f() const" << std::endl;}
};
A::~A(){
}
int main() {
const A a;
a.f();
return 0;
}
.\temp05.cpp: In constructor ‘A::A()’:
.\temp05.cpp:7:5: error: uninitialized const member in ‘const int’ [-fpermissive]
7 | A() {};
| ^
.\temp05.cpp:5:15: note: ‘const int A::i’ should be initialized
5 | const int i;
| ^