Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

const在c++中怎么用

作者:昔日暖阳   发布日期:2026-01-04   浏览:62

// 示例代码:const在C++中的用法

#include <iostream>
using namespace std;

// 1. 常量定义
const int MAX_SIZE = 100; // 定义一个常量,值不能被修改

// 2. const作为函数参数
void printValue(const int& value) {
    // value 在这个函数中是只读的,不能被修改
    cout << "The value is: " << value << endl;
}

// 3. const作为函数返回值
const int& getConstRef() {
    static int value = 42; // 使用静态变量确保引用的有效性
    return value;
}

// 4. 成员函数中的const
class MyClass {
public:
    void display() const { // const成员函数,保证对象状态不被修改
        cout << "Displaying data" << endl;
    }

private:
    int data;
};

int main() {
    // 使用常量
    cout << "MAX_SIZE: " << MAX_SIZE << endl;

    // 使用const作为函数参数
    int num = 5;
    printValue(num);

    // 使用const作为返回值
    const int& ref = getConstRef();
    cout << "Returned const reference: " << ref << endl;

    // 使用const成员函数
    MyClass obj;
    obj.display();

    return 0;
}

解释说明:

  1. 常量定义const int MAX_SIZE = 100; 定义了一个常量 MAX_SIZE,其值在程序运行期间不能被修改。
  2. const作为函数参数void printValue(const int& value) 中的 value 是只读的,不能在函数内部修改它。
  3. const作为函数返回值const int& getConstRef() 返回一个常量引用,调用者不能通过该引用修改返回值。
  4. 成员函数中的constvoid display() const 表示这是一个常量成员函数,在调用时不会修改对象的状态。

以上代码展示了 const 在 C++ 中的几种常见用法。

上一篇:chrono c++

下一篇:c++ 类初始化

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

c++virtual

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站