C++ const和mutable的使用
<上一节
下一节>
const修饰变量
在C++中,一般用const完全替代C语言的define,且功能更多。用const修饰变量,使之成为常量(或常数),这很简单,但结构体中成员如果用了const,需要注意,请看下面例子。
#include <iostream>
using namespace std;
typedef const double CONSTANT;
CONSTANT pi = 3.14159265;
struct mytype {
const int x;
int y;
};
int main ( )
{
//pi = 3.14; //编译出错,常量不能赋值
//常量定义必须有初始值
//mytype s; //编译出错,结构体中的x成员常量没有初始值
mytype s1 = {15, 20};
//s1.x = 3 //编译出错,常量不能赋值
s1.y = 100;
const mytype s2 = {25, 30};
//s2.y = 125; //编译出错,整个s2的所有成员都变成了常量
cout << "s1: " << s1.x << ", " << s1.y << endl;
cout << "s2: " << s2.x << ", " << s2.y << endl;
return 0;
}
运行结果:s1: 15, 100
s2: 25, 30
这一节的内容应该是C语言的内容,早期版本的C语言不支持const,现在已经完全支持。
const修饰类的成员函数
用const修饰类的成员函数,可以使函数内不能对任何成员变量修改。不是成员变量当然可以修改。
#include <iostream>
using namespace std;
class classA {
int x;
string y;
public:
void get(int& i, string& s) const {
int k;
k = 10; //非成员变量可以修改
//x = k; //成员变量不能修改
//y = "小雅"; //成员变量不能修改
i = x, s = y;
}
void set(int i, string s) { x = i; y = s; }
};
int main ( )
{
classA ca;
ca.set(100, "C语言中文网");
int i;
string s;
ca.get(i, s);
cout << s << "--" << i << endl;
return 0;
}
运行结果:C语言中文网--100
mutable与const为敌
用mutable修饰成员变量,可以使该成员变量即使在const成员函数中也能被修改。
#include <iostream>
using namespace std;
class classA {
int x;
mutable string y;
public:
void get(int& i, string& s) const {
int k;
k = 10; //非成员变量可以修改
//x = k; //成员变量不能修改
y = "小雅"; //mutable变量可以修改
i = x, s = y;
}
void set(int i, string s) { x = i; y = s; }
};
int main ( )
{
classA ca;
ca.set(100, "C语言中文网");
int i;
string s;
ca.get(i, s);
cout << s << "--" << i << endl;
return 0;
}
运行结果:C语言中文网--100
<上一节
下一节>
