C++常量

来源:百度知道 编辑:UC知道 时间:2024/06/16 11:34:26
#include<iostream.h>
class C0
{
/********found********/
int const n;int m;\\------------1
public:
explicit C0(int t)
/********found********/
: n(t)
{
m =0;
}

void Set(int y)
{
m = y;
}
void print()
{
cout<<"m="<<m<<" n="<<n;
cout<<endl;
}
};
void main()
{
/********found********/
C0 obj(3);
obj.Set(2);
obj.print();
}
1处为什么n能定义为const常量,而m不行。

const 常量必须在构造函数的初始化列表中初始化。

int const m;

explicit C0(int t)
/********found********/
: n(t), m(t)
{
//m =0;
}

const变量只能初始化,不能另外赋值(另类办法除外).
因为你在构造函数中,对m使用了赋值语句,所以如果在类中将限制为const,编译将出错....

将m与n一样放到初始化列表中:
...:n(t), m(t) {
...
}