【问题标题】:Pointer-to-member function resolution指向成员函数解析
【发布时间】:2012-12-01 19:46:22
【问题描述】:

这是一个用于过滤对象列表的函子。它必须用指向对象类的成员函数的指针来实例化,作为访问不同元素的一种方式。

class Filter_Compare : public Filter {
    std::string (File::*fun)();
public:
    Filter_Compare(const char *name, const char *desc, std::string (File::*f)())
        : Filter(name, desc), fun(f)
    {}
    ~Filter_Compare() {};

    int operator () (File* f1, File* f2) { return this->eval(*f1, *f2); }
    int eval(File* f1, File* f2) const { return this->eval(*f1,*f2); }

    int eval(File& f1, File& f2) const {
        return f1.*(this->fun()).compare(f2.*(this->fun()));
    }
};
//an instanciation example :
Filter_Compare fname("Name", "Compare by name", File::getPath);

而 g++ 返回这些错误:

Filter.h: 在成员函数'int Filter_Compare::eval(File&, File&) const': Filter.h:48:27: error: 必须使用'.' 或'->' 来调用 '((const) 中的指向成员函数的指针 Filter_Compare*)this)->Filter_Compare::fun (...)',例如'(...->* ((const Filter_Compare*)this)->Filter_Compare::fun) (...)' Filter.h:48:53: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘((const Filter_Compare*)this)->Filter_Compare::fun (...)',例如'(...->* ((const Filter_Compare*)this)->Filter_Compare::fun) (...)'

我在这里没有看到问题,因为我已经在另一个类上使用了它而没有任何错误(好吧,至少它可以编译,我现在无法运行它),代码在哪里:

lit_type eval(File& f) const { return f.*(this->fun()) - thValue; }

这里到底出了什么问题?我不知道如何以另一种方式引用指针。谢谢!

【问题讨论】:

    标签: c++ function-pointers pointer-to-member


    【解决方案1】:

    要通过指向成员函数的指针调用,请使用 .*->*。要在File& f1 上拨打fun,请拨打(f1.*fun)()。所以:(f1.*fun)().compare((f2.*fun)())。如果您想使用不需要的显式 this->s 来复杂化表达式,则必须格外小心:(f1.*(this->fun))().compare((f2.*(this->fun))())

    【讨论】:

    • 我认为你的括号也不对。我认为应该是(f1.*fun)()(即() 优先于.*
    • @DavidRodríguez-dribeas - 你可能是对的。这就是我不编译代码的结果。固定。
    【解决方案2】:

    括号错误:

    int eval(File& f1, File& f2) const {
        return (f1.*fun)().compare((f2.*fun)());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多