C++私有成员函数
发布时间:2020-12-16 07:38:27 所属栏目:百科 来源:网络整理
导读:到目前为止,我们所看到的所有类成员函数都是公共函数,这意味着它们可以通过类外部的程序代码调用。但是,类也经常需要一些函数来进行内部处理,这样的函数不应该由类外的代码调用,它们应该被声明为 私有 。 下面的程序显示了具有私有函数的类的示例。Simpl
到目前为止,我们所看到的所有类成员函数都是公共函数,这意味着它们可以通过类外部的程序代码调用。但是,类也经常需要一些函数来进行内部处理,这样的函数不应该由类外的代码调用,它们应该被声明为私有。 下面的程序显示了具有私有函数的类的示例。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 Program int 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |