c++ - 只读类成员 C++

标签 c++ getter getter-setter

我有点困惑,我读到在 C++ 中使用 getter 和 setter 有一些缺点,尽管创建只读变量、使变量私有(private)并创建 getter 函数似乎是显而易见的事情。 也许有一个简单的答案,我只是看不到它,但是什么是一个好的/更好的替代方案,可以使成员变量在没有 setter/getter 的情况下只读,或者使用 setter/getter 函数可以接受,甚至是解决这个问题的好方法?

最佳答案

a) 提供 getter 和 setter 和/或 b) 公共(public)数据属性

无法实现最佳耦合和内聚的软件工程目标。


来自维基百科:

In software engineering, coupling is the manner and degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules. Coupling is usually contrasted with cohesion.

In computer programming, cohesion refers to the degree to which the elements of a module belong together.[1] Thus, cohesion measures the strength of relationship between pieces of functionality within a given module. For example, in highly cohesive systems functionality is strongly related.


在过程编程中,(通常)有 8 个耦合级别(从最差到最好)。维基文章描述了所有这些。您的编码工作应该争取最佳耦合(带有标签“无”)。

(通常)有 7 个级别的内聚力排名(从最差到最好)。您应该努力实现最佳凝聚力(带有“功能性”标签)。


考虑耦合的一种方法 - 如果您添加 setter 和 getter 或使用公共(public)数据属性,为什么还要费心将这些数据封装到此类中?如果您允许代码的任何部分修改数据属性,那么请考虑当需求更改迫使您更改数据属性的名称和/或类型时,可能需要更改多少非类代码。

关于内聚性的类似想法——公共(public)数据属性很容易被不相关的代码(另一个对象或外部函数中的代码)修改,是什么让它们成为类的一部分的“不错的选择”?也许这些“外部”代码应该是您的对象的一部分......是与该对象为系统所做的主要“目标”相关的数据。

关于c++ - 只读类成员 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474846/

相关文章:

java使用getter和setter方法并返回0

python - 如果您不介意使用方法访问属性,是否值得使用 Python 的 @property 装饰器?

c++ - Visual Studio 无法在 bool 运算的上下文中实例化强制转换(转换)运算符模板 (T=bool)

c++ - 编译器会折叠结构相同的类吗?

c++ - 在 switch 语句中使用算术和逻辑运算符

swift - 什么时候调用计算属性的修改方法,它做什么?

java - Getter 函数未返回正确的值

c++ - 使用 extern 跨文件共享 const 时,为什么在定义中需要 extern?

dart - 什么时候应该在 dart 中使用 final 字段、工厂构造函数或带有 getter 的私有(private)字段?

java - 如何从 getter 返回的对象访问变量