本意是要設(shè)計(jì)一個(gè)存儲表的內(nèi)存結(jié)構(gòu)元扔,可是要求又比較奇特:既能提供類似vector的調(diào)用方式别伏,又能有map的特性码秉。于是自己設(shè)計(jì)了一個(gè)怪模怪樣的類:
class Table
{
std::vector<std::vector<std::string> > talbe_;
public:
Table();
int find(const int index, const char* value);
std::vector<std::string>& operator[](const int index);
int size();
int column_num();
};
但是這樣使用時(shí)吆录,主類的調(diào)用接口如果傳遞的是引用,比如下面這樣:
int get_table(const char* table_name, Table& table);
這里雖然傳遞了引用鲫售,仍然涉及一些內(nèi)存拷貝的事情共螺,而且構(gòu)造一個(gè)這樣的對象,開銷本是不必要的情竹,而如果使用一個(gè)指針的引用,比如:
int get_table(const char* table_name, Table*& table);
這樣使用時(shí)會出現(xiàn) (*table)[index]這樣怪異的寫法匀哄。
后來總算想到一種辦法秦效,將class Table中的 table_換為一個(gè)index,而Table由于要調(diào)用一些主類中的數(shù)據(jù)涎嚼,因此將Table聲明為主類的friend阱州。
大致是這樣的:
class Table
{
int index_;
public:
Table();
int find(const int index, const char* value);
std::vector<std::string>& operator[](const int index);
int size();
int column_num();
};
class ConfManager
{
friend class Table;
std::vector<std::string> conf_file_array_;
std::vector<std::string> so_file_array_;
std::vector<std::vector<std::vector<std::string> > > table_array_;
};
本來以為是萬事大吉,可是主類中要設(shè)置Table時(shí)法梯,又需要訪問Table::index_苔货,提供一個(gè)set方法又不好犀概,因此,只能再把主類作為Table的friend夜惭。這樣以來姻灶,又混亂不堪了。
最后靈光一閃诈茧,將Table作為主類的一個(gè)內(nèi)部類产喉,同時(shí),將主類作為Table的friend類敢会,這樣大家都可以訪問私有成員曾沈,而對于用戶卻又是透明的。如下:
class ConfManager
{
std::vector<std::string> conf_file_array_;
std::vector<std::string> so_file_array_;
std::vector<std::vector<std::vector<std::string> > > table_array_;
std::vector<std::string> table_name_array_;
public:
class Table
{
friend class ConfManager;
int index_;
public:
Table();
int find(const int index, const char* value);
std::vector<std::string>& operator[](const int index);
int size();
int column_num();
};
static ConfManager& get_conf_manager();
};
確實(shí)有一種渾然天成的味道鸥昏,為了外面使用方便塞俱,再加個(gè)typedef,如下:
typedef ConfManager::Table Table;
friend關(guān)鍵字吏垮,在effective c++中被詬病再三障涯,主要原因是它破壞了程序的封裝性。不過萬事萬物都有它存在的必要性惫皱,話說回來像樊,依賴于class,private旅敷,protected生棍,等等所維護(hù)的封裝性,都只存在于編譯期而已媳谁。真正讓人頭疼的涂滴,還是運(yùn)行起來的各種越界和泄漏。
原文時(shí)間(2014-3-13)