C++顶层const与底层const

const用于修饰常量,被其修饰的值无法被改变。

顶层const: 修饰指针,指针本身是个常量,不能改变所指地址。

底层const: 修饰值,指针所指向的值是个常量,无法被修改。

测试

int main() {

    int d1 = 1, d2 = 2;

    int* const p1 = &d1; // 顶层const

    const int* p2 = &d2; // 底层const

    *p1 = 2;

    p1 = p2; // 报错

    std::cout << "&d1: " << p1 << "\n d1: " << *p1 << "\n";

    *p2 = 1; // 报错

    p2 = p1;

    std::cout << "&d2: " << p2 << "\n d2: " << *p2 << "\n";

}
.\test.cpp: In function 'int main()':
.\test.cpp:26:8: error: assignment of read-only variable 'p1'
   26 |     p1 = p2; // ?     ~~~^~~~
.\test.cpp:28:9: error: assignment of read-only location '* p2'
   28 |     *p2 = 1; // ?     ~~~~^~~
posted @ 2025-01-08 00:18  RunTimeErrors  阅读(26)  评论(0)    收藏  举报