昨天有讲一个古老的设计:利用标头档将类别介面与实作拆开并预先编译用以隐藏实作细节但还是不够安全隐密,因为从标头档还是可以看到private的资料成员与方法成员,这时可用proxy class代理类别进一步隐藏来看看这好玩的范例。
第一个文件Implementation.h(10.24)中有我们要隐藏的原始码,第二个文件Interface.h(10.25)包含proxy class的介面,要注意的是有两段分别是class Implementation;定义一个Implementation类别,并在private底下宣告一个Implementation类别的指标,第三个文件Interface.cpp(10.26)是proxy class的实作,值得注意的是不仅include了Interface的介面也include了Implementation的程序码细节。
最後一个文件fig10_27.cpp就是精随了只include了Interface.h就是代理物件的介面,原始的Implementation类别被彻底隐藏,接着在main()中就是一般的Interface物件方法的操作.getValue()与.setValue(),因为有解构式的存在就不用手动delete回收物件。讲完了不知大家有没有觉得C++真简单,话说那麽简单的语言绝对不能只有我学过,我已经成功拉一个成大经济系的学第入坑了比老鼠会还邪恶ㄏㄏ。
class Implementation
{
public:
// constructor
Implementation( int v )
: value( v ) // initialize value with v
{
// empty body
} // end constructor Implementation
void setValue( int v )
{
value = v; // should validate v
} // end function setValue
int getValue() const {
return value;
} // end function getValue
private:
int value; // data that we would like to hide from the client
}; // end class Implementation
// Client sees this source code, but the source code does not reveal
// the data layout of class Implementation.
class Implementation; // forward class declaration required by line 17
class Interface
{
public:
Interface( int ); // constructor
void setValue( int ); // same public interface as
int getValue() const; // class Implementation has
~Interface(); // destructor
private:
// requires previous forward declaration (line 6)
Implementation *ptr;
}; // end class Interface
// Implementation of class Interface--client receives this file only
// as precompiled object code, keeping the implementation hidden.
#include "Interface.h" // Interface class definition
#include "Implementation.h" // Implementation class definition
// constructor
Interface::Interface( int v )
: ptr ( new Implementation( v ) ) // initialize ptr to point to
{ // a new Implementation object
// empty body
} // end Interface constructor
// call Implementation's setValue function
void Interface::setValue( int v )
{
ptr->setValue( v );
} // end function setValue
// call Implementation's getValue function
int Interface::getValue() const
{
return ptr->getValue();
} // end function getValue
// destructor
Interface::~Interface()
{
delete ptr;
} // end ~Interface destructor
// Hiding a class’s private data with a proxy class.
#include <iostream>
using std::cout;
using std::endl;
#include "Interface.h" // Interface class definition
int main()
{
Interface i( 5 ); // create Interface object
cout << "Interface contains: " << i.getValue()
<< " before setValue" << endl;
i.setValue( 10 );
cout << "Interface contains: " << i.getValue()
<< " after setValue" << endl;
return 0;
} // end main
>>: Day4- Java语言编译器:javac & 运行工具:java (上)
缘由: 从UIUX那边总是会收到各种有趣的需求,这次收到的新需求为希望launch页面可以停止个几秒...
前言 今天会将昨天训练好的翻译模型在测试资料集进行预测,若进度符合期待,将会使用 BLEU 分数来评...
目前为止Glue的三个工具,可以依使用者的开发习惯与技术背景来选用,而AWS是以客户为导向的公司,对...
Oracle row to column在10G版本仅能使用 CASE or DECODE,11G版...
常常有人说做好一个企划需要勇气,但绝非这麽简单,创业不只需要勇气还需要运气、人脉、实力 、执着 做好...