基类中常见的受保护数据成员? [英] Common protected data member in base class?

查看:147
本文介绍了基类中常见的受保护数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类和几个派生类。派生类使用一些常见的数据,我可以把这些公共数据作为基类的受保护成员吗?我知道受保护的成员有时会打破封装,所以我想知道是否有任何好的方法。

I have a base class and several derived classes. The derived classes use some common data, can I just put those common data as protected member of the base class? I know the protected member breaks encapsulation sometimes, so I wonder if there is any good approach.

下面是一个具体的例子:

Here is a specific example:

class Base{
public:
   virtual void foo() = 0;
   void printData();
protected:
   std::vector<std::string> mData;
}

class Dr1 : public Base{
public:
   virtual void foo(); //could change mData
}

class Dr2 : public Base{
public:
   virtual void foo(); //could change mData
}



如果我把mData放入Dr1和Dr2作为私有成员,然后我需要把它放在它们两个,我不能有printData()在Base,因为printData()需要访问mData,除非我做printData()虚拟,并在Dr1和Dr2具有相同的功能, t对我有意义。

If I put mData into Dr1 and Dr2 as private member, then I need to put it in both of them, and I can not have printData() in Base since printData() need access to mData unless I make printData() virtual and have identical function in both Dr1 and Dr2, which doesn't make much sense to me.

有没有更好的方法来处理这个没有使用受保护的成员?谢谢。

Is there a better way to approach this without using protected member? Thank you.

推荐答案

要考虑的一个设计是使mData私有,并向Base提供受保护的方法然后可以由Dr1和Dr2使用。

One design to consider is making mData private, and adding protected methods to Base that provide common manipulations to the data that can then be used by Dr1 and Dr2.

但是有很多次将mData作为受保护成员更有意义。最好的方法将取决于你的班级的细节。

But there are plenty of times it makes more sense to leave mData as a protected member. The best approach will very much depend on the details of your class.

这篇关于基类中常见的受保护数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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