下面有两段示例代码:
#include <iostream>
#include <vector>
using namespace std;
class emp {
int emp_count;
public:
emp() { emp_count=2; }
int get_employee_count() const { return emp_count; }
};
int main() {
const emp e1;
cout << e1.get_employee_count();
return 0;
}
上面的代码工作正常。但是,以下代码在尝试更改只读值时会出现错误:
#include <iostream>
#include <vector>
using namespace std;
class emp {
const int emp_count;
public:
emp() { emp_count=2; }
int get_employee_count() const { return emp_count; }
};
int main() {
emp e1;
cout << e1.get_employee_count();
return 0;
}
const 类对象不允许我更改数据成员的值,但根据上面的示例,const 类对象与const 数据成员 因为我可以在第一段代码的构造函数主体中分配值,而第二段代码限制我做同样的事情?
最佳答案
const 类对象不允许在构造函数之外修改其任何数据成员的值。例如:
#include<iostream>
#include<vector>
class emp {
public:
int emp_count; // Made public for demonstration
emp() { emp_count = 2; }
int get_employee_count() const { return emp_count; }
};
int main()
{
const emp e1;
emp e2;
e1.emp_count = 10; // Compiler error
std::cout << e1.get_employee_count();
return 0;
}
但是 emp_count 仍然可以通过构造函数修改:
emp()
{
emp_count = 2; // This is assignment, not initialization
}
const数据成员是初始化后不能修改的数据成员,无论是在类内部还是在类外部。
要初始化数据成员,只需为其分配一个值,如下所示:
class emp
{
const int emp_count = 2;
public:
或者使用构造函数初始化它:
class emp
{
const int emp_count;
public:
emp() : emp_count(2) { } // Initialization of emp_count
int get_employee_count() const { return emp_count; }
};
此外,请考虑不在代码中使用以下行:
using namespace std;
..因为这被认为是不好的做法。
关于c++ - const 类对象与 const 数据成员有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71196253/