如何在c++中访问私有嵌套类

How to access a private nested class in C++?

本文关键字:嵌套 访问 c++      更新时间:2023-10-16

我在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
不可见的是类的名称,但只要不需要实际使用其名称,就可以构造它。