C ++ 类 | 类与数组(Array)_4

类与数组的例子

对于此程序,请使用以下 类 来练习:

使用 Dog类 创建动物收容所名册。在 Dog类 中添加一个构造函数。 狗的初始名称是 " Unknown ";

声明并定义函数:

printRoster(roster,SIZE);

okay,我们直接上码:

using namespace std;

class Dog
{
    string name;
    int licenseNumber;
public:
    Dog();
    void setName(string nameIn);
    void setLicenseNumber(int licenseNumberIn);
    string getName();
    int getLicenseNumber();
    void printInfo();
};

Dog::Dog()
{
     name="Unknown";
}

void Dog::setName(string nameIn)
{
    name = nameIn;
}

void Dog::setLicenseNumber(int licenseNumberIn)
{
    licenseNumber = licenseNumberIn;
}

string Dog::getName()
{
    return name;
}

int Dog::getLicenseNumber()
{
    return licenseNumber;
}

void Dog::printInfo()
{
    cout<<name<<" "<<licenseNumber;
}

以上代码保存在 dog.cpp 文件里。

#include<iostream>
#include "Dog.cpp"

using namespace std;

void printRoster(Dog roster[], int size);

void printRoster(Dog roster[], int size)
{
    for(int i=0;i<size;i++)
    {
        roster[i].printInfo();
        cout<<"\n\n";
    }
}

以上代码作为头文件 main.hpp 。

#include "main.hpp"


int main()
{
    //ToDo: assign the dogs to an array called roster
    //Then assign names to the Dog.
    
    //ToDo: declare and define this function
    //in the header file
    const int SIZE=3;
    Dog roster[SIZE];

    roster[0].setName("Blue");
    roster[1].setName("King");
    roster[2].setName("Spot");

    printRoster(roster,SIZE);
    return 0;
}

运行结果:

代码解析:

void printRoster(Dog roster[], int size);

这里是创建一个 无返回值 的 函数printRoster(单词意思:打印花名册),这里重点注意 Dog roster[],这里的 roster[] 是可以调用Dog类的函数和值的。

void printRoster(Dog roster[], int size)
{
    for(int i=0;i<size;i++)
    {
        roster[i].printInfo();
        cout<<"\n\n";
    }
}

做 for 循环,让roster[i]打印出每行的信息,然后打印两个回车。注意这里的输出结果,我们没有输入license,其实内存暂时分配。


假如编程易懂得,那么程序员就不会热情地写出注释,也不会有得到编程的快乐。

猜你喜欢

转载自blog.csdn.net/sw3300255/article/details/84844566