// 示例代码: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;
}
const int MAX_SIZE = 100; 定义了一个常量 MAX_SIZE,其值在程序运行期间不能被修改。void printValue(const int& value) 中的 value 是只读的,不能在函数内部修改它。const int& getConstRef() 返回一个常量引用,调用者不能通过该引用修改返回值。void display() const 表示这是一个常量成员函数,在调用时不会修改对象的状态。以上代码展示了 const 在 C++ 中的几种常见用法。
上一篇:chrono c++
下一篇:c++ 类初始化
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站