我的程序中有一个结构
struct secret_structure{
string a;
string b;
void *c;
};
Run Code Online (Sandbox Code Playgroud)
我有这样的结构清单
std::map<string name, secret_structure> my_map
Run Code Online (Sandbox Code Playgroud)
我必须编写一个函数,通过将其与名称映射来返回结构.
get_from_map(string name, secret_structure * struct) //Kind of function
Run Code Online (Sandbox Code Playgroud)
我有以下选择:
在get_from_map函数中传递secret_structure的指针.get_from_map填充结构.我不想这样做,因为结构将被暴露.
我可以使用不同的函数从结构中返回不同的值.这里的结构不会暴露,但看起来不干净.
你能帮我解决任何其他选择,使结构本身不暴露.
您可以传递包含指向真实对象的指针的句柄,而不是传递结构:
// public_interface.h
struct MySecretStruct; // I don't want to publish what's inside
struct WhatYouCanSee
{
MySecretStruct *msp; // The "P"ointer to "IMPLE"mentation
WhatYouCanSee(int a, double b);
~WhatYouCanSee();
WhatYouCanSee& operator=(const WhatYouCanSee&);
WhatYouCanSee(const WhatYouCanSee&);
void method1();
void method2(int x);
};
Run Code Online (Sandbox Code Playgroud)
这些方法只是调用真实对象方法的包装器.