在C语言和C++中有一个很特殊的关键词——const,这个关键词表示常量的意思,一旦被该关键词修饰后,则该变量变成了一个常量,const可以修饰变量,也可以修饰指针,也可以修饰引用,同样地,const也可以用来修饰类或结构体中的属性或方法。const的好处之一就是防止后续程序中修改不允许变动的值,以避免产生bug。如下面的程序,就是一个典型的方法可以改变对象中的属性:
#include <iostream>
using namespace std;
struct A{
int m, n;
void f(){ //调用这个方法将改变这个类的属性
m++;
n++;
}
};
int main(){
A a1 = {1, 2};
A a2 = {5, 6};
a1.f(); //改变对象a1的属性
a2.f(); //改变对象a2的属性
在这种情况下,对象的属性很容易被改变,如果这时我不想某一对象中的属性时,这时可用const修饰该对象,如:
#include <iostream>
using namespace std;
struct A{
int m, n;
void f(){ //同样地,该方法修改了类中的属性
m++;
n++;
}
};
int main(){
const A a1 = {5, 6}; //用const修饰对象a1,说明a1是个常量对象,属性不允许被修改
A a2 = {5, 6}; //非常量对象
a1.f(); //产生编译错误,a1为常量对象,其属性不允许被修改
a2.f(); //合法
}
值得注意的是,被const修饰的对象不能调用类中没有被const修饰的方法,例如上面的对象a1不能调用方法f,但可以调用被const修饰的方法。但是没有被const修饰的对象是可以调用被const修饰的方法的,例如下面的程序:
#include <iostream>
using namespace std;
struct A{
int m, n;
void f() const { //该函数被const修饰
cout << m << "\t" << n << endl;
}
};
int main(){
const A a1 = {3, 4}; //被const修饰的对象a1
A a2 = {5, 6}; //未被const修饰的对象a2
a1.f(); //合法,因为方法f也被const修饰
a2.f(); //合法,虽然a2未被const修饰,但也可以调用被const修饰的方法
}
输出结果:
一旦类中的方法被const修饰了,则意味着该方法为常量,方法中不得有修改类中属性的语句存在,例如:
struct A{
int m, n;
void f() const {
m++; //产生编译错误,此处修改了类中的属性
int d = 0;
d++; //合法,d不是类中的属性,可以被修改
}
};
同样地,被const修饰的方法也不允许调用其他能够修改类中属性的其他方法,例如:
struct A{
int m, n;
void h(){
m++;
n++;
}
void f() const {
h(); //产生编译错误,方法h修改了类中的属性,方法f被const修饰,不得调用方法h
}
一般地,在一些类的方法中,如果需要将属性作为返回值的,或者需要以文本形式输出的方法都会用const修饰,如下面的程序:
#include <iostream>
using namespace std;
class Complex{
int re;
int im;
public:
void setCom(int r, int i){
re = r;
im = i;
}
int getReal() const { //该函数用const修饰,因为仅仅是以实部作为返回值
return re;
}
int getImag() const { //同样地用const修饰
return im;
}
void text() const { //以文本形式输出,也用const修饰
cout << "this complex number is : << re << " + " << im << "j" <<endl;
}
};
int main(){
Complex com1;
com1.setCom(5, 6);
cout << com1.getReal() << endl;
cout << com1.getImag() << endl;
com1.text();
}
输出结果:
如有错误,欢迎大家批评与指正!