如何在c++中访问私有嵌套类
How to access a private nested class in C++?
我在CPP测验中发现了一个问题。问题是
class secret
{
class hidden{};
public:
template <class K>
string accept(K k) {return (k(*this, hidden()));}
string keyToNextLvl (hidden )const {return ("success!"); }
};
struct SampleSoln
{
template <class pwd>
string operator()(const secret &sc, pwd opwd) const
{ return (sc.keyToNextLvl(opwd)); }
};
int main()
{
secret sc;
cout <<sc.accept(SampleSoln()) << endl; //Prints success
cout <<sc.keyToNextLvl (AnswerKey()) << endl; //Need to provide the implementation of AnswerKey
}
现在我必须使用"keyToNextLvl"方法直接访问它。(我不允许访问accept方法-使用accept方法访问keyToNextLvl的示例解决方案在ques本身中提供。所以我需要提供AnswerKey)
的实现我做了一些搜索,得到了一些方法来访问私有成员/方法,而不使用朋友http://bloglitb.blogspot.in/2010/07/access-to-private-members-thats-easy.html
明白了!
struct AnswerKey
{
template <class T>
operator T ()
{
return T();
}
};
使用模板化的转换操作符构造一个secret::hidden
对象
因为它是默认可构造的,你可以这样做:
sc.keyToNextLvl ({})
例如:
#include<string>
#include<iostream>
class secret
{
class hidden{};
public:
template <class K>
std::string accept(K k) {return (k(*this, hidden()));}
std::string keyToNextLvl (hidden )const {return ("success!"); }
};
int main()
{
secret sc;
std::cout <<sc.keyToNextLvl ({}) << std::endl;
}
您不需要定义AnswerKey
。
不可见的是类的名称,但只要不需要实际使用其名称,就可以构造它。
相关文章:
- 无法访问嵌套类.类的使用无效
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- C++将结构传递给函数以访问嵌套结构
- 嵌套容器:为什么我无法访问堆栈队列顶部的堆栈?C++
- 通过 id 访问 QML 插槽中的嵌套对象(从 c++ 调用)
- 如何访问嵌套类的数据?
- 访问另一个类中的模板化嵌套类函数和对象
- 如何访问嵌套在命名命名空间中的未命名命名空间变量?
- 优雅地访问嵌套类中的数据
- 无法从多态嵌套类访问包含类的成员
- 嵌套的类成员变量不可访问.链表设置.V、下一个和新的问题
- 访问range_expression中的嵌套元素会返回不完整的映射(段错误)
- 如何通过迭代器访问向量中的嵌套对?
- 在 c++ 中访问嵌套字典unordered_map<字符串、void*>?
- Python和Ctypes访问带有嵌套结构的C 类
- 为什么 clang 不允许通过实例访问嵌套枚举类?
- 访问嵌套块中重新定义的变量
- C++对不同功能的私有嵌套访问
- 通过指向成员的指针对嵌套访问进行编译时评估期间出现 GCC 错误