自学内容网 自学内容网

设计一个Dog类,包含name、age、sex和weight等属性以及对这些属性操作的方法。实现并测试这个类。

完成以下要求:

  1. 类放到头文件dog.h中、成员函数定义文件放到源文件dog.cpp中、主函数放到源文件mian.cpp文件中。
  2. 根据类的封装性要求,把name、age、sex和weight声明为私有的数据成员,编写公有成员函数setdata()对数据进行初始化;
  3. GetName()、GetAge()、GetSex()和GetWeight()获取相应属性;
  4. SetName(string )、SetAge(int )、SetSex(char )和SetWeight(double )能够修改相应属性。
  5. 使用带有默认参数的构造函数对对象进行初始化;
  6. 使用析构函数,在函数中可以输出对象的相应属性。
  7. 声明多个对象,观察构造函数的调用顺序和析构函数的调用顺序。

没注释的源代码

#include <iostream>

#include<string>

#include "dog.h"

using namespace std;

void Dog::setdata()

{

    name="zhangsan";

    age=18;

    sex='m';

    weight=15;

}

void Dog::GetName()

{

    cout<<"name:"<<name<<endl;

}

void Dog::GetAge()

{

    cout<<"age:"<<age<<endl;

}

void Dog::GetSex()

{

    cout<<"sex:"<<sex<<endl;

}

void Dog::GetWeight()

{

    cout<<"weight:"<<weight<<endl;

}

void Dog::SetName(string n)

{

    name=n;

}

void Dog::SetAge(int a)

{

    age=a;

}

void Dog::SetSex(char s)

{

    sex=s;

}

void Dog::SetWeight(double w)

{

    weight =w;

}

Dog::Dog(string n,int a,char s,double w):name(n),age(a),sex(s),weight(w){}

Dog::~Dog()

{

    cout<<"destructor called"<<" "<<name<<" "<<age<<" "<<sex<<" "<<weight<<endl;

}

//新建一个文件

#include <iostream>

#include "dog.h"

using namespace std;

int main()

{

    Dog d1;

    d1.GetName();

    d1.GetAge();

    d1.GetSex();

    d1.GetWeight();

    Dog d2("wangwu",16,'m',20);

    d2.setdata();

    d2.GetName();

    d2.GetAge();

    d2.GetSex();

    d2.GetWeight();

    Dog d3("dog3",17,'m',21);

    d3.SetName("dog4");

    d3.SetAge(16);

    d3.SetSex('f');

    d3.SetWeight(30);

    d3.GetName();

    d3.GetAge();

    d3.GetSex();

    d3.GetWeight();

    return 0;

}

#include<string>

using namespace std;

class Dog

{

private:

    string name;

    int age;

    char sex;

    double weight;

public:

    void setdata();

    void GetName();

    void GetAge();

    void GetSex();

    void GetWeight();

    void SetName(string );

    void SetAge(int );

    void SetSex(char );

    void SetWeight(double );

    Dog(string n="lisi",int a=16,char s='f',double w=10);

    ~Dog();

};


原文地址:https://blog.csdn.net/2303_80770781/article/details/142825370

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!