作者tinlans ( )
看板C_and_CPP
标题Re: [问题] class继承问题 请教
时间Wed Oct 28 07:23:10 2009
※ 引述《QQ29 (我爱阿蓉)》之铭言:
: 4.有个不解的地方是 老爸的private资料明明就继承给儿子
: 儿子看的到却不能用 顶多透过 老爸的function去修改数值
: 然後要get时 再透过老爸的get function去get...
: 这样为啥不直接老爸就写成protected就好
: 有没有什麽case是老爸必定要写private 不然会有什麽漏洞或是什麽问题产生?
基本上 OO 程式的原则,
就是所有 data members 都要是 private,
想开放给儿子去存取是把 setter/getter 标成 protected,
不准儿子存取就是连这两样都 private 掉甚至是不提供,
这单纯只是类别的封装概念而已,
所以为了符合这种概念都会把 data members 直接 private 起来。
如果你不想探讨概念性的东西,
真的是有必要的例子也很好找,
像是你为了加快程式速度可能会写类似这样的东西:
class MyClass {
public:
...
ResultT query() const;
private:
...
mutable ResultT cache_;
mutable bool initialized_;
};
ResultT MyClass::query() const
{
if(initialized_) return cache_;
else {
cache_ = ...;
initialized_ = true;
return cache_;
}
}
只要这个 query method 被执行过一次,
那就能快速的取得结果,
被执行过一次的状态用 initialized_ 这个 data member 去记录,
之前算出来的结果暂存在 cache_ 这个 data member,
一般来说你绝对不会希望 initialized_ 这种东西被儿子随便修改吧?
--
Ling-hua Tseng (
[email protected])
Department of Computer Science, National Tsing-Hua University
Interesting: C++, Compiler, PL/PD, OS, VM, Large-scale software design
Researching: Software pipelining for VLIW architectures
Homepage:
https://www.tinlans.org
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.160.115.152
※ 编辑: tinlans 来自: 118.160.115.152 (10/28 07:25)
1F:推 VictorTom:推....:) 10/28 09:21
2F:推 ledia:真是简明易懂, 推~ 10/28 11:40
3F:推 QQ29:谢谢t大 我知道意思了 10/28 14:58