C++中const全局常量与const函数内常量的区别
时间: 2024-03-17 17:41:38 浏览: 83
C++中的const关键字可以用来定义常量,它的作用是使变量的值不可修改。但是在不同的使用场景下,const关键字的含义可能会有所不同。
全局常量是在程序开头定义的,它的作用域是从定义处到文件结尾,可以被整个文件内的函数访问。定义全局常量时,需要在前面加上const关键字,表示这是一个常量。例如:
```
const int MAX = 100; // 定义全局常量MAX
```
函数内常量是在函数内部定义的,只能在该函数内部使用。定义函数内常量时,同样需要在前面加上const关键字,表示这是一个常量。例如:
```
void func()
{
const int MAX = 100; // 定义函数内常量MAX
}
```
区别在于,全局常量的作用域是整个文件,而函数内常量的作用域仅限于该函数。此外,全局常量在程序运行期间都是存在于内存中的,而函数内常量只在函数执行期间存在于内存中,在函数执行完毕后就被销毁了。
相关问题
c++中const和static关键字
### C++ 中 `const` 和 `static` 关键字的用法与区别
#### 常量特性 (`const`)
在C++中,`const`用于定义不可变的数据。一旦初始化后,这些数据就不能再被修改。
- **常量变量**
定义一个常量整数如下所示:
```cpp
const int MAX_SIZE = 10;
```
- **常量指针与指针常量**
可以创建指向常量对象的指针以及本身为常量的指针:
```cpp
char *p = "hello"; // p是指向字符数组的可变指针
const char *q = "world"; // q是指向字符数组的只读指针
char* const r = str; // r是一个指向char类型的常量指针
```
- **常量引用**
创建对某个特定值的别名而不允许通过该别名更改原值:
```cpp
void func(const int& ref) {
// 不得修改ref的内容
}
```
- **常量成员函数**
成员函数后面加上`const`表明此方法不会改变类的状态。
- **常量函数参数和返回值**
函数形参列表中的`const`限定符确保传入的对象不被改动;而返回类型前加上的`const`则防止接收方篡改返回的结果[^1]。
#### 存储持续性和作用域 (`static`)
另一方面,`static`主要影响程序元素的作用范围及其生存期:
- **局部静态变量**
当在一个函数体内声明了一个带有`static`修饰符的局部变量时,则意味着这个变量在整个应用程序执行期间都保持有效,并且仅第一次进入该函数体的时候才会被执行初始化操作。
```cpp
void counter() {
static int count = 0;
++count;
std::cout << "Count is now: " << count << '\n';
}
```
- **类的静态成员**
对于类而言,静态成员属于整个类而不是单个实例化出来的对象。因此所有的对象共享同一个静态成员副本。
```cpp
class MyClass {
public:
static int sharedValue;
};
int MyClass::sharedValue = 42; // 初始化外部链接的静态成员变量
```
- **全局/命名空间级别的静态变量**
如果希望某些变量仅仅局限于当前源文件内可见的话就可以采用这种方式来实现隐藏效果。
```cpp
namespace Ns {
static int hiddenVar = 98765;
}
```
综上所述,虽然两者都可以用来限制访问权限,但是它们各自有着不同的侧重点——`const`强调的是保护数据免受意外变更的影响,而`static`更侧重于调整实体的存在形式(比如延长生命周斯或是缩小可视区域)。
const 函数 是成员函数 还是全局函数
const 是 C++ 中的一个关键字,用来修饰数据类型、指针、函数等,表示它们是常量。在这里,const 并不是函数的类型,因此不能说 const 函数是成员函数还是全局函数。
在 C++ 中,const 成员函数是一种特殊的成员函数,它被声明为 const 类型,表示该函数不会修改对象的状态。const 成员函数可以被 const 对象调用,也可以被非 const 对象调用,但是非 const 对象调用 const 成员函数时,只能调用该函数的 const 版本。例如:
```c++
class Example {
public:
void func() const {
// const 成员函数
}
void func() {
// 非 const 成员函数
}
};
int main() {
const Example ex1;
ex1.func(); // 只能调用 const 版本的 func
Example ex2;
ex2.func(); // 调用非 const 版本的 func
const Example& ex3 = ex2;
ex3.func(); // 只能调用 const 版本的 func
return 0;
}
```
在上面的例子中,我们定义了一个类 Example,其中包含两个名为 func 的函数,一个是 const 成员函数,一个是非 const 成员函数。在 main 函数中,我们分别定义了三个对象 ex1、ex2 和 ex3,其中 ex1 是 const 对象,ex2 是非 const 对象,ex3 是 ex2 的一个 const 引用。
当我们调用 ex1.func 时,只能调用 const 版本的 func;而当我们调用 ex2.func 时,只能调用非 const 版本的 func;当我们调用 ex3.func 时,也只能调用 const 版本的 func。
阅读全文
相关推荐
















