【问题标题】:Define and use private methods not in header file定义和使用不在头文件中的私有方法
【发布时间】:2016-11-06 12:23:32
【问题描述】:

我有一种情况,不允许我修改我的班级的头文件。我只想添加一个辅助函数来与我的一个函数一起使用.. 但不能完全弄清楚实现它的正确方法。通常我会尝试谷歌,但在那里找不到任何帮助。

这是我当前的代码:

    template<typename T>
void Set<T>::doubleRotateRight(Elem *& node) {
    // you fill in here
    rotateRight(node->left);
    rotateLeft(node);

    //call private helper not defined in header
    privmed();

}
void privmed(){
    //out << "who" << endl;
}

但是,当我运行它时,我得到了错误:

error: there are no arguments to ‘privmed’ that depend on a template parameter, so a declaration of ‘privmed’ must be available [-fpermissive]
     privmed();

对此的任何帮助都将令人难以置信!

【问题讨论】:

  • 在 C++ 中,所有东西都必须在使用前声明。您是否尝试过将 privmed 函数实现移到 doubleRotateRight 函数之前?
  • 投票结束为不清楚。需要关于什么可以修改和什么不能修改的信息;需要有关privmed 的用途的信息;需要有关目标的信息。
  • cmon.... 非常感谢
  • “我不允许修改头文件”。您显示的代码在那个头文件中,不是吗?
  • @CaptainGiraffe 代码在 .cpp 文件中。我可能错了,但很确定那不是标题

标签: c++


【解决方案1】:

你可以只使用一个 lambda:

template<typename T>
void Set<T>::doubleRotateRight(Elem *& node)
{
    static auto const privmed = []() -> void 
    {
        //out << "who" << endl;
    };

    // you fill in here
    rotateRight(node->left);
    rotateLeft(node);

    //call private helper not defined in header
    privmed();
}

【讨论】:

  • 好吧,然后声明一个本地类并在该类中使用static 成员函数。
  • 或者,根据您的意思,您可以使用 lambda 调用 doubleRotateRight 函数或其他一些反过来调用它的函数。如果没有一个非常具体的问题,就很难草拟解决方案。但是任何递归都是可行的:如何去做取决于它是什么。
  • 当我运行你发布的代码时,它只是说“‘privmed’没有命名类型”
  • 我的目标是能够运行该辅助函数并让它递归调用自己
  • 我不认为那是我发布的代码,你得到了那个错误。您需要更清楚地了解事物(例如,您的头文件是什么,您的目标是什么,究竟如何递归)才能获得好的答案,而不是偶然。'
【解决方案2】:

我认为问题是你必须在使用它之前定义“privmed()”函数,像这样:

void privmed(){
    //out << "who" << endl;
}

template<typename T>
void Set<T>::doubleRotateRight(Elem *& node) {
    // you fill in here
    rotateRight(node->left);
    rotateLeft(node);

    //call private helper not defined in header
    privmed();
}

【讨论】:

  • 据我了解,这与头文件混淆,OP 被限制这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多