bear七 2022-04-24 23:07 采纳率: 83.3%
浏览 72
已结题

c++设计类的问题解答


#include"iostream"
using namespace std;
class person{
protected:
 int age;
 int height;
 double weight;
 static int num;
public:
 person(int a,int h,double w):age(a),height(h),weight(w){ num++; }
 void Show(){
  cout << "age: " << "height:  " << "weight:   "  << endl ;
  cout << age << "   " << height << "       " << weight << endl ;
 }
 static int number(){
  return num;
 }
};
 
int person::num=0;
 
int main()
{
 person a(10,30,140),b(20,60,170);
 a.Show();
 b.Show();
 cout << "person:" << endl ;
 cout << person::number() << endl ;
}

请问怎么把这个代码改成输入格式为“按姓名、年龄、身高和体重依次输入每个人的信息,以exit结束”
这是原本的题目“设计一个People 类,该类的数据成员有姓名、年龄、身高、体重和人数,其中人数为静态数据成员,成员函数有构造函数、显示和显示人数。其中构造函数由参数姓名、年龄、身高和体重来构造对象;显示函数用于显示人的姓名、年龄、身高和体重;显示人数函数为静态成员函数,用于显示总的人数。”
非常感谢!

  • 写回答

2条回答 默认 最新

  • aabyte 2022-04-25 00:05
    关注

    如有帮助望采纳

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    class Person
    {
        public:
            string name;
            int age;
            int height;
            double weight;
            static int num;
        public:
            Person()
            {
                num++;
            }
            Person(string name,int age,int height,double weight)
            {
                this->name = name;
                this->age = age;
                this->height = height;
                this->weight = weight;
                num++;
            }
            void show()
            {
                cout <<"name:" <<name<< "\tage:" << age<<"\theight:"<<height<<"\tweight:"<<weight<<endl;
            }
            static int number()
            {
                return num;
            }
    };
    
    int Person::num = 0;
    
    int main()
    {
        cout<<"按姓名、年龄、身高和体重依次输入每个人的信息,以exit结束"<<endl;
        vector<Person> ps;
        while(true)
        {
            Person* p = new Person();
            cin>>p->name;
            if(p->name == "exit")
            {
                break;
            }
            cin>>p->age>>p->height>>p->weight;
            ps.push_back(*p);
        }
        for(int i = 0; i < ps.size(); ++i)
        {
            ps[i].show();
        }
        cout << "the number of person: " ;
        cout << Person::number() - 1<< endl ;
        return 0;
    }
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月3日
  • 已采纳回答 4月25日
  • 创建了问题 4月24日