繁体   English   中英

高阶函数应用于数组

[英]Function from a higher order applied to an array

我有一个特定类的向量;

vector<Song> database;

class Song
{
public:
    string getName() const;
    string getSinger() const;
    unsigned int getLength();
    unsigned short getYear() const;

private:
    char singer[51];
    char name[51];
    unsigned int length;
    unsigned short year;
};

请注意,向量不在Song类之内。 在另一堂课。 在那个其他的类中,我以更高的顺序创建了一个函数。 该函数的参数之一是Song类的getter:

void order(string, int, Song*, unsigned int (Song::*get)(), bool(*compare)(unsigned int, unsigned int));

但是,当我这样拨打电话时:

database[a].(obj->*get())

我了解到,当我必须处理其他类中的函数时,必须引用该类的对象,同时还要引用该类中的函数。 我的问题是我是否可以传递一个函数引用来自动检测正在使用的对象?

编辑

void Interface::order(string command, int findLength,
    Song* obj, unsigned int (Song::*get)(), bool(*compare)(unsigned int first, unsigned int second))
{
    for (unsigned int a = 0; a < database.size(); a++)
    {
        if (compare(database[a].(obj->*get)(), stoi(command)))
        {
            cout << "Deleting found match...\n";
            database.erase(database.begin() + a);
        }
    }
}

我在database[a].(obj->*get)()错误。错误是编译器需要成员名称。 但是,我想提供一个不依赖于已传递的对象的函数。 换句话说,我要问的是是否有一种构造类型可以让我在此处传递一个函数作为参数,并且该函数会自动(从歌曲的向量中)调用每个对象及其相应的getter方法。

您正确地了解通过成员函数指针访问成员函数的->*语法:这是当您有指向对象的指针时的语法。

通过成员对象访问成员函数还有另一种语法:

(database[a].*get)()

这将调用在database[a]上的Song对象上的get指向的成员函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM