尝试总结一下const关键词在C++中的用法,不一定全面和正确,希望大家拍砖,共同进步。
参考:
1、替换#define
用const可以在编译阶段进行type检查,避免不必要的错误
-
const int size = 100; //编译器可能会把size放在symbol table里面,而不分配变量内存
-
int array[size];
2、作为一个只初始化一次,不可变的内存块
-
const int array[] = {10, 20, 30}
-
int set[array[1]] //《Think in C++》里说会报错,但是貌似G++没有报错。
3、关于const指针
-
const int* a
-
int const* a // 这两个是等价的,即指针指向的int不能改
-
-
int * const a // 指针的指向是不可变的,但是所指的内容是可变的。
-
-
// 一般用从右向左原则
4、关于传参
如果不想让函数调用影响传入的参数,可以有一下三种方式
-
void foo(const string &str)
-
void foo(const string *str)
-
void foo(string str) //这要copy,效率低
5、const成员函数
-
#include <iostream>
-
-
using namespace std;
-
-
class A {
-
public:
-
A() {} //默认构造函数要显式提供,不然 const A ca;无法初始化。
-
-
void f() {
-
cout << "f()" << endl;
-
}
-
-
void f() const {
-
cout << "f() const " << endl;
-
}
-
};
-
-
int main() {
-
A a;
-
a.f();
-
const A ca;
-
ca.f();
-
-
return 0;
-
}
-
-
运行结果:
-
f()
-
f() const
从这个例子看出const是作为函数f()的function signature的;同时在函数重载时候,const对象调用const成员函数,non-const对象调用非const成员函数。
6、利用const形参进行函数重载
-
void foo(int i)
-
void foo(const int i)
上面的两个函数重载是无法完成的,编译器会报 redefine错误。其实仔细分析一下是有道理的,例如代码foo(3);编译器根本无法选择一个函数来执行。
-
void foo(const int &i)
-
void foo(int &i)
而这样是可以的,因为引用会影响外部调用的。
7、const修饰函数返回类型
一般要在有返回引用或者指针时候用到。
-
#include <iostream>
-
-
using namespace std;
-
-
class MyArray {
-
public:
-
MyArray() {}
-
int& operator[](int i) {
-
return array[i];
-
}
-
-
private:
-
int array[100];
-
};
-
-
void print(const MyArray &array) {
-
cout << array[1] << endl;
-
}
-
-
int main() {
-
MyArray myArray;
-
myArray[1] = 100;
-
cout << myArray[1] << endl;
-
print(myArray); // 报错
-
-
return 0;
-
}
这里在print函数中,array是const对象,但是array[1]返回了引用,这是无法保证array是不变的,所以要加一个返回const引用 的const成员函数。
-
#include <iostream>
-
-
using namespace std;
-
-
class MyArray {
-
public:
-
//MyArray() {}
-
int& operator[](int i) {
-
return array[i];
-
}
-
-
const int& operator[](int i) const{
-
return array[i];
-
}
-
-
private:
-
int array[100];
-
};
-
-
void print(const MyArray &array) {
-
cout << array[1] << endl;
-
}
-
-
int main() {
-
MyArray myArray;
-
myArray[1] = 100;
-
cout << myArray[1] << endl;
-
print(myArray);
-
-
return 0;
-
}
阅读(390) | 评论(0) | 转发(0) |