c++设计一个小狗类并测试

设计一个小狗类Dog,具有多个属性和方法如下图所示,请编写Dog类并用主函数测试:

img

其中Init()初始化3个属性,position初值为0,Speak() 屏幕打印“汪汪”,Run()每次调用都使position+1,Info()函数以字符串形式返回小狗的整体信息,格式自定。

你题目的解答代码如下:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Dog
{
    int age;
    string color;
    string type;
    int position=0;

public:
    Dog()
    {
        cout << "创建一个Dog对象" << endl;
    }
    ~Dog()
    {
        cout << "销毁一个Dog对象" << endl;
    }
    void Init(int age,string color,string type)
    {
        this->age = age;
        this->color = color;
        this->type = type;
        this->position = 0;
    }
    void Speak()
    {
        cout << "汪汪" << endl;
    }
    void Run()
    {
        position++;
    }
    string Info()
    {
        stringstream ss;
        ss << "Dog Info." << endl;
        ss << "age:" << age << endl;
        ss << "color:" << color << endl;
        ss << "type:" << type << endl;
        ss << "position:" << position << endl;
        return ss.str();
    }
};
int main()
{
    Dog d1;
    d1.Init(1,"white","哈士奇");
    d1.Speak();
    d1.Run();
    cout << d1.Info() << endl;
    return 0;
}

img

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img