微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c++中的函数对象《未完成》

文件

#pragma once
#include<iostream>
#include<vector>
using namespace std;
class Student
{
public:
    Student(double hei):height(hei){}
    double getheight() const { return height; }
    ~Student(){}
private:
    double height;
};

vector<Student> s;
for(int i=0;i<5;i++)
    s.???
// 定义一个函数对象类
// 用于统计容器中所有Student对象的身高
class AverageHeight
{
public:
    // 构造函数,对类的成员变量作合理的初始化
    AverageHeight()
        : m_nCount(0), m_nTotalHeight(0) {};
    // 定义函数调用操作符“()”,
    // 在其中完成统计功能
    void operator () (const Student& st)
    {
        // 将当前对象的身高累加到总身高中
        // 这里的m_nTotalHeight记录了上次累加的结果,
         // 这就是函数那失去的记忆
        m_nTotalHeight += st.getheight();
        // 增加已经统计过的Student对象的数目
        ++m_nCount;
    }
    // 接口函数,获得所有统计过的Student对象的平均身高
    float GetAverageHeight()
    {
        if (0 != m_nCount)
            return (float)GetTotal() / GetCount();
    }
    // 获得函数对象类的各个成员变量
    int GetCount() const
    {
        return m_nCount;
    }
    int GetTotal() const
    {
        return m_nTotalHeight;
    }
    // 函数对象类的成员变量,
    // 用来保存函数执行过程中的状态数据
private:
    int m_nCount;  // 记录已经统计过的对象的数目 
    int m_nTotalHeight;  // 记录已经统计过的身高总和
};
View Code

文件

#include"wuyong.h"
using namespace std;
int main()
{
    // 创建函数对象
    AverageHeight ah;
    //函数对象应用到for_each()算法中以完成统计
    ah = for_each(vecStu.begin(), vecStu.end(), ah);
    //函数对象中获取它的记忆作为结果输出
    cout << ah.GetCount() << "个学生的平均身高是:"
        << ah.GetAverageHeight() << endl;
    system("pause");
    return 0;
}
View Code

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐