C ++类设计编码问题 [英] C++ class design coding question

查看:83
本文介绍了C ++类设计编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有效的c ++第22项中,Scott Meyers说数据成员必须是私人的。



我的问题是,如果有A类,那就是类的父类B和C,A有数据成员int id。



如果A将int id私有,B类和C类应该使用A的getter和setter导致性能下降。



下面的示例代码。



In effective c++ Item 22, Scott Meyers say data member must be in private.

My question is, if there is class A, which is parent of class B and C, and A has data member "int id".

if A put "int id" in private, class B and C should use A's getter and setter, which cause reduction in performance.

example code in below.

class A
{
public:
  int getId() { return id; }
  void setId(int id) { id_ = id; }
private:
  int id_;
};

class B : public A
{
public:
  int getId() { return A::getId(); }
  void setId(int id) { A::setId(id); }
}

class C : public A
{
public:
  int getId() { return A::getId(); }
  void setId(int id) { A::setId(id); }
};





我很困惑。有人帮我做我应该做的事吗?



I'm confused. Anybody help me what I should do?

推荐答案

首先,请参阅解决方案1,它很好地解释了这个问题。

First, see solution 1, it explains the issue pretty well.

除此之外, getId setId 函数(在您的情况下)是隐式内联,所以在这种情况下你不必为减少性能而烦恼。

In addition to that, the getId and setId functions (in your case) are implicitly inline, so you don't have to bother with reduction in performance in this case.


1)首先注意,类B和C从类A继承getID()和setID()(这是两者的父级)所以你应该从类B中删除它们C类!



2)通常可以忽略使用get或set方法丢失的性能,建议使用get()和set()代替直接访问。



3)如果您想直接从B类或C类访问id__,您可以将其访问权限从私有更改为受保护。
1)First note, the classes B and C inherits getID() and setID() from class A (that is the parent for both) so you should delete them from class B and class C!

2)In generally the performance lost by using of get or set methods can be ignored, and it is recommended to use get() and set() in place of direct access.

3)If you want to access directly the id__ directly from class B or C you could change its access from private to protected.


这篇关于C ++类设计编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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