Give some examples of const usage in c++
时间: 2024-03-07 14:50:27 浏览: 69
Sure, here are some examples of `const` usage in C++:
1. Constants: You can use `const` to declare constants in C++. For example:
```
const int MAX_SIZE = 100;
const double PI = 3.14159;
```
2. Function parameters: You can use `const` in function parameters to ensure that the function does not modify the parameter. For example:
```
void print(const std::string& str) {
std::cout << str;
}
```
3. Pointers and references: You can use `const` with pointers and references to declare them as "read-only". For example:
```
const int* ptr = &MAX_SIZE;
const std::string& message = "Hello, world!";
```
4. Member functions: You can use `const` in member functions to indicate that the function does not modify the object's state. For example:
```
class MyClass {
public:
int getValue() const {
return value;
}
private:
int value;
};
```
5. Return values: You can use `const` in function return types to indicate that the returned value is read-only. For example:
```
const std::string getMessage() {
return "Hello, world!";
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)