程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 類和函數-請問這道題用C++怎麼做?關於類的

類和函數-請問這道題用C++怎麼做?關於類的

編輯:編程綜合問答
請問這道題用C++怎麼做?關於類的

建立一個person類,包含姓名、性別、年齡三個公有字段,另包含males、females兩個公有靜態字段成員,用來記錄男、女的人數,建立一個teacher類和一個student類,這兩個類都繼承person類,teacher包含工號,工資字段,student包含學號,班級字段,在main函數裡面增加幾個學生對象和老師對象,然後統計男女總人數,並且分別打印所有所有教師和學生的信息。

最佳回答:


#include
#include
using namespace std;

class Person
{
public:
string name;
string sex;
int age;
static int males;
static int females;
};

int Person::males = 0;
int Person::fmales = 0;

class Teacher: Person
{
public:
string workNum;
string salve;

Teacher(string name, string sex, int age, string workNum, string salve)
{
    this->name = name;
    this->sex = sex;
    this->age = age;
    this->workNum = workNum;
    this->salve = salve;

    if (this->sex == "nan")
    {
        males++;
    }
    else if (this->sex == "nv")
    {
        females++;
    }
}

};

class Student: Person
{
public:
int stuNum;
int classNum;

Student(string name, string sex, int age, int stuNum, int classNum)
{
    this->name = name;
    this->sex = sex;
    this->age = age;
    this->stuNum= stuNum;
    this->classNum= classNum;

    if (this->sex == "nan")
    {
        males++;
    }
    else if (this->sex == "nv")
    {
        females++;
    }
}

};

int main()
{
Student stu1("aa", "nan", 13, 1, 1);
Student stu2("bb", "nan", 14, 2, 2);
Teacher ter1("cc", "nan", 26, "001", "5000");
Teacher ter2("dd", "nv", 26, "007", "5000");

cout << "Student:" << endl;
cout << "name:" << stu1.name << "sex:" << stu1.sex << "age:" << stu1.age 
     << "stuNum:" << stu1.stuNum << "classNum:" << stu1.classNum << endl;
cout << "name:" << stu2.name << "sex:" << stu2.sex << "age:" << stu2.age 
     << "stuNum:" << stu2.stuNum << "classNum:" << stu2.classNum << endl;
cout << "Teacher:" << endl;
cout << "name:" << ter1.name << "sex:" << ter1.sex << "age:" << ter1.age 
     << "workNum:" << ter1.stuNum << "salve:" << ter1.salve << endl;
cout << "name:" << ter2.name << "sex:" << ter2.sex << "age:" << ter2.age 
     << "workNum:" << ter2.stuNum << "salve:" << ter2.salve << endl;

cout << "males:" << Person::males << endl;
cout << f"males:" << Person::fmales << endl;

return 0;

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved