构造函数或访问器以及成员样式? [英] Constructors or Accessors and member style?

查看:119
本文介绍了构造函数或访问器以及成员样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个问题.

首先,似乎只是添加一个新的构造函数比向类中添加一堆mutator函数以创建新实例更好.你同意吗?还是添加mutator更好,还是构造函数有问题?

另外,如果m_Variable代替了存取器函数,如果它们在容纳m_variable的类的函数内部,可以使用样式吗?

There are two questions.

The first is that it seemed better to just add a new constructor than add a bunch of mutator functions to a class in order to create a new instance. Would you agree? Or would it be better to add mutators, or are constructors problematic?

Also, it it OK style to use the m_Variable instead of accessor functions if they''re inside functions of the class that house the m_variable?

推荐答案

时间,除非有充分的理由不这样做.大多数类实际上不需要更改或读取一个状态位的函数.通常,如果您考虑的是对象行为而不是行为方式,则不会发现拥有设置者/更改者"的很多原因.
在成员函数内部,没有必要使用任何访问函数.如果您拥有它们,并且它们除了读取一些数据之外还能做一些有用的事情,那么您也可以使用它们,但我不会为内部使用而编写新的代码.

干杯,

Ash
Go for constructors every time unless there''s a good reason not to. Most classes don''t actually need functions to change or read one squitty bit of state. Generally if you think about an objects behaviour rather than how it does it you won''t find a lot of reasons to have "setters/mutators."

Inside member functions there''s no point in using any access functions. If you''ve got them and they do something useful apart from just read back a bit of data then you might as well use them but I wouldn''t bother writing new ones just for internal use.

Cheers,

Ash


这完全取决于您-对此没有硬性规定.具有多个构造函数重载是非常典型的,通常不认为是有问题的.当然,您可以将它过长,使它成为维护的噩梦.

是的,可以在类中使用私有字段.
It''s up to you really - there are no hard rules on this. Having multiple constructor overloads is fairly typical and is not normally considered problematic. Of course you can take it too far and make it a maintenance nightmare.

And yes, it''s fine to use the private field from within the class.


这篇关于构造函数或访问器以及成员样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆