注册 登录
编程论坛 C++教室

求助大神 !! 类函数模板 用函数做参数提示 student::bujige”: 非静态成员函数的非法调用

滚落的石子 发布于 2013-11-20 17:10, 465 次点击
#include <iostream>
#include <string>

class student;

template <typename T, class fun>
int my_count_if(T *a,int n,fun f) //f 是判断特征的函数
{
    int count = 0;
    for ( int i=0; i<n; ++i    )
    {
        if (a[i].f)
        {
            count ++;
        }
    }
    return count ;
}




class student
{
private:
    int score;
    std::string  name;
public:
    student(int a=0,char* s="")
        :score(a),name(s){}

    student (const student& s)
    {
        if (this!=&s)
        {
            this->name=s.name;
            this->score=s.score;
        }
    }

    student &operator=(const student&rhs)
    {
        if (this!=&rhs)
        {
        this->name=rhs.name;
        this->score=rhs.score;
        }
        return *this;
    }

    bool bujige()    //定义不及格的函数
    {
        return score<60;
    }

  
};

int main()
{
    student a[]={student(50,"tom"),student(49,"jerry"),student(91,"henry")};
    int n=sizeof(a)/sizeof(*a);
    int num=my_count_if(a,n,student::bujige);
}

//其中bujige是作为一个判定性质的函数
5 回复
#2
blueskiner2013-11-20 17:26
bujige()必须依赖Student实体对象

a[0].bujige()这样调用才是合法的
#3
yuccn2013-11-20 18:46
bujige。。
用个英文命名好懂点
#4
rjsp2013-11-21 08:48
随便改了一下
程序代码:
#include <cstddef>

template<typename T, class MF>
size_t my_count_if( const T* a, size_t n, MF f )
{
    size_t count = 0;
    for( size_t i=0; i!=n; ++i )
    {
        if( (a[i].*f)() )
        {
            ++count;
        }
    }
    return count;
}

template<typename T, size_t N>
size_t my_count_if2( const T (&a)[N], bool (T::*memfun)() const )
{
    size_t count = 0;
    for( size_t i=0; i!=N; ++i )
    {
        if( (a[i].*memfun)() )
        {
            ++count;
        }
    }
    return count;
}

#include <string>

class student
{
public:
    explicit student( int a=0, const char* s="" ) : score_(a), name_(s)
    {
    }

    student( const student& s ) : score_(s.score_), name_(s.name_)
    {
    }

    student& operator=( const student& rhs )
    {
        if( this != &rhs )
        {
            name_ = rhs.name_;
            score_ = rhs.score_;
        }
        return *this;
    }

    bool flunk() const
    {
        return score_<60;
    }

private:
    int score_;
    std::string name_;
};

#include <iostream>
using namespace std;

int main()
{
    student a[] = { student(50,"tom"), student(49,"jerry"), student(91,"henry") };

    size_t n = sizeof(a)/sizeof(a[0]);
    size_t num = my_count_if( a, n, &student::flunk );
    cout << num << endl;

    cout << my_count_if2(a,&student::flunk) << endl;

    return 0;
}

#5
滚落的石子2013-11-23 17:59
回复 4楼 rjsp
谢谢啊
#6
滚落的石子2013-11-23 17:59
回复 3楼 yuccn
恩恩
1