首页 > 代码库 > 类和对象-4
类和对象-4
一个考试成绩结果统计的小程序,共3个文件
Analysis.h:头文件声明
// Analysis.h // Definition of class Analysis that analyzes examination results. // Member-function is defined in Analysis.cpp // Analysis class definition class Analysis { public: // process 10 students‘ examination results void processExamResults(); }; // end class Analysis
Analysis.cpp:统计分析的具体实现
// Analysis.cpp // Member-functions for class Analysis that // analyzes examination results #include <iostream> using std::cout; using std::cin; using std::endl; // include definition of class Analysis from Analysis.h #include "Analysis.h" // process the examination results of 10 students void Analysis::processExamResults() { // initializing variables in declaration int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result ( 1 = pass, 2 = fail ) // process 10 students using counter-controlled loop while (studentCounter<=10) { // prompt user for input and obtain value from user cout << "Enter result ( 1 = pass, 2 = fail )"; cin >> result; // input result // if...else nested in while if (result == 1) // if result is 1 { passes++; // increment passes, } else // if result is not 1, so { failures++; // increment failures } studentCounter++; // increment studentCounter to loop eventually terminates } // end while // termination phase: display number of passes and failures cout << "Passed: " << passes << "\nFailures: " << failures << endl; // determine whether more than 8 students passes if( passes >= 8 ) cout << "Raise tuition!\n"; } // end function processExamResults
test.cpp:测试文件
// test.cpp // Test program for class Analysis #include "Analysis.h" int main() { Analysis application; // create Analysis object application.processExamResults(); // call function to process results return 0; // indicate successful termination } // end main
良好的编程习惯
与二元运算符不同,一元的自增和自减运算符应该紧邻其操作数,中间不能有任何数据
常见的编程错误
企图用表达式(不是一个可修改变量的名字和引用),例如++(x+1),作为自增或自减运算符操作将是一个语法错误
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。