【问题标题】:How to set up a number of objects如何设置多个对象
【发布时间】:2021-12-20 05:27:50
【问题描述】:
void Dog::readDog()
{
    cout << "Name: ";
    cin >> this->name;
    cout << "height: ";
    cin >> this->height;
    cout << "weight: ";
    cin >> this->weight;
    cout << "Color: ";
    cin >> this->color;
}
void Dog::printDog()
{
    cout << "Name: " << this->name << endl;
    cout << "Height: " << this->height << endl;
    cout << "Weight: " << this->weight << endl;
    cout << "Color: " << this->color << endl;
}

int main() {
    Dog dogs;
    int n;
    cout << "Number of dogs to introduce: ";
    cin >> n;
    
    dogs.readDog();
    dogs.printDog();

}

这是我的代码的一部分,我有一个小问题,因为我忘记了如何设置一些我想在程序中引入的狗,例如我想要 3 条狗:Max、Rex、Terry。我的程序只读取和打印一只狗

【问题讨论】:

    标签: c++ class


    【解决方案1】:

    您可以使用std::vector 创建一个容器,该容器将包含 n 数量的Dog 对象,如下所示:

    #include <iostream>
    #include <vector>
    #include <string>
    class Dog 
    {
      public:
          void readDog();
          void printDog();
      private:
        std::string name, color;
        double height, weight;
    };
    
    void Dog::readDog()
    {
        std::cout << "Name: ";
        std::cin >> this->name;
        std::cout << "height: ";
        std::cin >> this->height;
        std::cout << "weight: ";
        std::cin >> this->weight;
        std::cout << "Color: ";
        std::cin >> this->color;
    }
    void Dog::printDog()
    {
        std::cout << "Name: " << this->name << std::endl;
        std::cout << "Height: " << this->height << std::endl;
        std::cout << "Weight: " << this->weight << std::endl;
        std::cout << "Color: " << this->color << std::endl;
    }
    
    int main() {
        Dog dogs;
        int n;
        std::cout << "Number of dogs to introduce: ";
        std::cin >> n;
        
        std::vector<Dog> vecDogs(n); //create a vector (of size n) of Dog objects 
        for(int i = 0; i < n; ++i)
        {
            vecDogs.at(i).readDog();
            vecDogs.at(i).printDog();
        }
        
    }
    

    std::vector 是一个可变大小的容器,这意味着您可以使用它来拥有n 数量的Dog 对象,其中n 不需要是一个常量表达式。

    以上程序的输出可见here

    【讨论】:

    • 谢谢你的提醒!
    • @my_name 不客气。如果对您有帮助,您能否将此答案标记为正确?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 2012-10-18
    相关资源
    最近更新 更多