抽象类中的data member如何处理? 我发现,我的具体类要访问一个数据成员
那么,我如何处理?
1) priavte
另外添加一个protected型的函数
2) 直接使用protected的数据成员
大家觉得哪种方式好?
那么,我如何处理?
1) priavte
另外添加一个protected型的函数
2) 直接使用protected的数据成员
大家觉得哪种方式好?
既然是抽象类,一般都是用其子类的成员函数访问。方法一可以保证数据的封装。虽然protected型的data member也只是用子类的成员函数访问。可是如果要定义一个一般型的类,最好还是private,由函数访问。我觉得这样更符合OOP的思想。你觉得呢?
抽象类很少使用private我想使用protected应该够了大家说,以后会有什么麻烦?
所以,还是用protected比较好,已足够安全了
大家看看,我们再讨论。When you allow direct access to private members, whether by making
them public, or even protected, you make it impossible for the member
functions of the base class to predict everything that might happen to
their data members. Thus, those functions cannot be closed. They may
need to be modified because some derived class, used the data member
in an unexpected way.Generally, you should make your data members private. If you feel
that derived classes will need access to them, then you can provide
protected accessor functions which allow for their manipulation in
predictable ways.Granted, this does interfere (slightly) when you want to reuse a class
by deriving from it. However it breaks the dependency of the derived
class upon the base data member. And breaking that dependency is
the more important of the two.Ideally, you would like all of your inheritance to be from abstract
base classes that specify pure virtual functions and no data members
at all. In practice, this is not a practical goal, however the spirit
of that goal is still important. Try to derive from abstract base
classes where possible. Move data members as low in the inheritance
hierarchy as practical. If you must access data members from derived
classes, use protected accessor functions to do so. Ideally, write
abstract base classes that declare those protected member functions to
be pure virtual, so that there is no dependency on the real form of
the data whatever.
例如:
现在使用数组
以后可以改成list来有优化。