主要学习下简单的构造函数构造:
#include <iostream> using std::cout; using std::cin; using std::endl; #include <string> using std::string; using std::getline; class GradeBook { private: string courseName; public: GradeBook():courseName(""){}; GradeBook(string s):courseName(s){}; void setName(string newName) { courseName = newName; } void displayMessage()//形参 { cout << "Welcome to the grade book for " << courseName << "!" <<endl; } }; int main() { string nameOfCourse;//创建string类型变量,用语存储输入课程名称 cout << "Please enter the course name:" << endl;//提示输入课程名称 getline(cin,nameOfCourse);//通过getline库函数执行输入,从用户那里读取名称赋值给nameOfCourse cout << endl; GradeBook myGradeBook1(nameOfCourse); myGradeBook1.displayMessage(); GradeBook myGradeBook2(); myGradeBook2.setName(nameOfCourse); myGradeBook2.displayMessage(); return 0; }