c++ - const 类对象与 const 数据成员有何不同?

标签 c++ oop constructor constants

下面有两段示例代码:

#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/

相关文章:

C++模板替换错误

C++ 命名空间和包含

c# - 在 .net 中转换期间对象会发生什么变化?

mysql - 这种情况下最好的 Ruby 类设计/模式是什么?

c# - 将实例的克隆分配给基本接口(interface)

java - 构造函数与 Java 中的普通方法有何不同?

javascript - Javascript 构造函数有什么意义?

c++ - 将 Char* 分配给字符串变量后删除

c++ - 包含值地址的字符串 -> 该值的指针

c++ - 从 C++ 中的基类继承复制/移动构造函数作为构造函数