题目2

来源:互联网 发布:数据迁移工程师 编辑:程序博客网 时间:2024/06/02 07:30
1.创建一个 Person 类,拥有属性 age、weight,并添加其构造器方法和构造

函数(包括一个无参的构造函数和一个带两个参数的构造函数)。

//第一题class Person {public:    Person() { }    Person(int age, double weight) : age(age), weight(weight) { }    void setAge(int age) { this->age = age; }    int getAge() const { return this->age; }    void setWeight(double weight) { this->weight = weight; }    double getWeight() const { return this->weight; }private:    int age;    double weight;};


2.创建一个 Student 类派生于 Person 类,拥有属性 grade,同样有构造器方

法和构造函数(要求同上),构造函数可以调用基类的构造函数并传参。

//第二题class Person {public:    Person() { }    Person(int age, double weight) : age(age), weight(weight) { }    void setAge(int age) { this->age = age; }    int getAge() const { return this->age; }    void setWeight(double weight) { this->weight = weight; }    double getWeight() const { return this->weight; }protected:    int age;    double weight;};class Student : public Person {public:    Student() { }    Student(int age, double weight, int grade) : Person(age, weight), grade(grade) { }    void setGrade(int grade) { this->grade = grade; }    int getGrade() const { return this->grade; }protected:    int grade;};



3.对 Person 类添加一个 sayHello()方法,该方法输出“你好! 。对 Student
类也添加一个 sayHello()方法,输出“你好我也好,大家好才是真的好!。定义
一个指向 Person 类的指针,令其指向一个 Student,并且调用 sayHello()方法,
使其输出的是“你好我也好,大家好才是真的好!(与 Student 类的 sayHello()方法

一样)

//第三题#include <iostream>using namespace std;class Person {public:    Person() { }    Person(int age, double weight) : age(age), weight(weight) { }    void setAge(int age) { this->age = age; }    int getAge() const { return this->age; }    void setWeight(double weight) { this->weight = weight; }    double getWeight() const { return this->weight; }    virtual void sayHello() const {        cout << "你好!" << endl;    }protected:    int age;    double weight;};class Student : public Person {public:    Student() { }    Student(int age, double weight, int grade) : Person(age, weight), grade(grade) { }    void setGrade(int grade) { this->grade = grade; }    int getGrade() const { return this->grade; }    virtual void sayHello() const {        cout << "你好我也好,大家好才是真的好!" << endl;    }protected:    int grade;};int main() {    Person* person = new Student(16, 140.0, 9);    person->sayHello();    return 0;}


4.了解私有继承、受保护继承和公有继承,用自己的语言阐述一下区别。