正如标题所暗示的那样,我一直认为要设置常量值并且无法修改但是我注意到你能够在构造函数中更改它.正如您所看到的,我创建了一个字符串名称,稍后将其设置为我通过构造函数的任何内容,为什么这允许?
示例代码:
#include <iostream>
using namespace std;
class test{
const string name;
public:
test(const string &nam) : name(nam) {}
string get_name() { return name; }
};
int main ()
{
test a("Tom");
cout << a.get_name();
// const string t1;
// string t2 = "changing"; this causes an error
// t1 = &t2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)