
下面的程序显示了具有私有函数的类的示例。SimpleStat 类被设计用于从发送给它的一组非负整数中查找和报告信息,如平均值和最大数字。但是,一旦某个数字已经被接收并被添加到累计汇总,那么它将不被保留,所以该类不能等以后再确定哪个数字是最大的,它必须通过检查其读取的每个数字来查看它是否大于之前读取的任何数字。isNewLargest 私有函数正是执行此 *** 作的。
#include <iostream>using namespace std;class SimpleStat{ private: int largest; // The largest number received so far int sum; // The sum of the numbers received int count; // How many numbers have been received bool isNewLargest(int); // This is a private class function public: SimpleStat(); // Default constructor bool addNumber(int); double getAverage(); int getLargest() { return largest; } int getCount() { return count; }};SimpleStat::SimpleStat(){ largest = sum = count = 0;}bool SimpleStat::addNumber(int num){ bool goodNum = true; if (num >= 0) // If num is valID { sum += num; // Add it to the sum count++; // Count it if(isNewLargest(num)) // Find out if it is largest = num; // the new largest } else //num is invalID goodNum = false; return goodNum;}bool SimpleStat::isNewLargest(int num){ if (num > largest) return true; else return false;}double SimpleStat::getAverage(){ if (count > 0) return static_cast<double>(sum) / count; else return 0;}//ClIEnt Programint main(){ int num; SimpleStat statHelper; cin >> num; while (num >= 0) { statHelper.addNumber(num); cin >> num; } cout << "\nYou entered "<< statHelper.getCount() << " values. \n"; cout << "The largest value was " << statHelper.getLargest () << endl; cout << "The average value was " << statHelper.getAverage () << endl; return 0;}程序输出结果:7 6 8 8 9 7 7 -1
You entered 7 values.
The largest value was 9
The average value was 7.42857
以上是内存溢出为你收集整理的C++私有成员函数全部内容,希望文章能够帮你解决C++私有成员函数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)