[英]Please explain how this is implemented
我所看到和被教授的关于封装的内容是我们可以将数据成员作为私有,成员函数是公共的。
但是C ++ Primer将封装定义为:
从接口分离实现; encapsulation隐藏了类型的实现细节。 在C ++中,通过将实现放在类的私有部分来强制执行封装。
最后一行是令人困惑的部分: 将实现放在类的私有部分中 。 通过实现,他意味着函数定义,对吗? 我的意思是,我从未见过一个声明为public(作为原型)并在私有中实现的函数。
我真的很困惑。 请用一个简单的例子来解释他想说的话。
被解释的概念比你想到的更抽象。 “接口”是“呼叫者期望对象做什么”。 从技术上讲,实现是如何实际执行这些操作的。
例如,拿一个List
类。 使用 List
代码应该只关心它的接口: addObject()
, clear()
, getSize()
, sort()
。
但是List
的实现 - 呼叫者不应该关心 - 可能在如何实现这一点上有很大的不同。 例如,数据可以存储为链表。 或者可能是动态数组。 这是“私有”实现细节,只有List
类需要关注。 确实可能有一个名为reallocate()
的private:
方法。 来电者不应该使用这个; 它是一个实现细节 - 不是公共接口的一部分。 调用者不应该关心List
如何分配其存储。
类似地, sort()
方法意味着它将对列表中的对象进行排序。 那就是界面。 但是实现可以使用任意数量的算法来执行排序。 实现是一个私人细节 - 可以用私人方法完成。 在任何情况下,它都对呼叫者隐藏。
template<typename T>
class List
{
public:
// public members are part of the interface: the externally-visible behavior "contract" your object guarantees.
void addObject(const T& obj)
{
// call private methods to help carry out implementation.
ensureCapacity(this->sizeAllocated + 1);
this->sizeAdvertized += 1;
// ... and copy the object into the right position in this->data...
}
size_t getSize() const
{
return this->sizeAdvertized;
}
// ... other members like clear(), sort()...
private:
T* data;
size_t sizeAllocated;
size_t sizeAdvertized;
// this needs to be private because it's not part of the interface. Callers
// should never need to call this.
void ensureCapacity(size_t requestedCapacity)
{
if(sizeAllocated >= requestedCapacity)
return;// already have enough storage available.
// ... reallocate this->data, copy existing items to the new array...
this->sizeAllocated = requestedCapacity;
}
};
最后要解决你说的话:
我的意思是,我从未见过一个声明为public(作为原型)并在私有中实现的函数。
“私人”再次比你想象的更抽象。 类的实现基本上总是 “私有”,因为它对调用者是隐藏的。 它不一定意味着private:
access说明符。 它只是意味着它不会暴露给呼叫者。 公共方法的实施符合这种描述。
你确实可以在一个类中拥有私有函数(方法)。 考虑:
class X
{
public:
// public interface - this never changes and you provide documentation for it
void do_something();
private:
// this private interface is likely to change. consumers of this class
// are prevented from calling these methods unless they are friends
void first_private_thing();
void second_private_thing();
};
// definition
void X::do_something()
{
// private implementation in public method
first_private_thing();
second_private_thing();
}
这个主题还有进一步的扩展,例如:
class Base
{
public:
// public non-virtual interface
void do_something();
private:
// calls private virtual implementation
virtual void do_something_impl() = 0;
};
// definition:
void Base::do_something()
{
do_something_impl();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.