// Classroom exercises: 课堂练习 // ce // 类的定义和使用 #include #include using namespace std; class Person { public: void init(const char *iname, int iage); void setName(const char sname[]); void setAge(int sage); const char *getname(); const int getAge(); const void show(); private: char name[32]; int age; }; void Person::init(const char *iname, int iage) { strcpy(this->name, iname); if (iage > 0 && iage < 100) this->age = iage; else { this->age = 0; cout << "年龄超出范围,拒绝赋值!" << endl; } } void Person::setName(const char sname[]) { strcpy(this->name, sname); } void Person::setAge(int sage) { if (sage > 0 && sage < 100) this->age = sage; else { cout << "年龄超出范围,拒绝赋值!" << endl; } } const char *Person::getname() { return this->name; } const int Person::getAge() { return this->age; } const void Person::show() { cout << "name = " << this->name << ", age = " << this->age << endl; } int main() { Person p1; p1.setAge(20); p1.setName("flykhan"); p1.show(); Person p2; p2.init("hello", 0); p2.show(); return 0; }