如何根据用户输入创建和访问多个对象 - C ++

时间:2017-03-02 04:24:37

标签: c++ object user-input

int main()
{
    string name, sound, owner;
    int age;
    int answer = 1;
    int i = 0;

    do
    {
        ++i;
        puts("Enter the dog info below");
        puts("Dog's name: ");
        cin >> name;
        puts("Dog's sound: ");
        cin >> sound;
        puts("Dog's age: ");
        cin >> age;
        puts("Dog's owner: ");
        cin >> owner;

        puts("Do you want to add one more dogs to the database?\n1: Yes\n0:     No");
        cin >> answer;

        Dog name(name, sound, age, owner);

    } while (answer != 0);

    for (int a = i; i > 0; i--)
    {
        printf("%s", name.getname().c_str());
        printf("\n\n%s is a dog who is %d years old, says %s and %s the owner\n\n",
            name.getname().c_str(), name.getage(), name.getsound().c_str(), name.getowner().c_str());
    }
    return 0;
}

这是根据用户输入创建多个对象的简单代码。我已经设置了类和方法。它没有do while循环就可以正常工作。但我无法根据用户输入创建对象并打印它们。以下行显示错误"没有成员getname。"每个被调用的方法都有相同的错误。我明白为什么会这样,但有没有解决方案?

name.getname().c_str(), name.getage(), name.getsound().c_str(), name.getowner().c_str());

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。

首先:您在不同的范围中声明了两个具有相同名称的变量:string name范围内的main()Dog name范围内的do ... whileDog对象仅存在于do ... while循环内。当您尝试在循环外部访问它时,您会收到错误... has no member getname,因为您实际上正在访问string对象,而不是Dog对象。

第二:您没有存储用户输入的Dog信息。

您需要使用向量来存储Dog个对象:

#include <vector>

int main()
{
    string name, sound, owner;
    int age;
    int answer = 1;
    std::vector<Dog> dogs; // Vector to store Dog objects

    do
    {
        puts("Enter the dog info below");
        puts("Dog's name: ");
        cin >> name;
        puts("Dog's sound: ");
        cin >> sound;
        puts("Dog's age: ");
        cin >> age;
        puts("Dog's owner: ");
        cin >> owner;

        puts("Do you want to add one more dogs to the database?\n1: Yes\n0:     No");
        cin >> answer;

        Dog dog(name, sound, age, owner);
        dogs.push_back(dog); // store current dog's info

    } while (answer != 0);

    for (int a = 0; a < dogs.size(); a++)
    {
        Dog& dog = dogs.at(a); // Get the dog at position i

        printf("%s", dog.getname().c_str());
        printf("\n\n%s is a dog who is %d years old, says %s and %s the owner\n\n",
            dog.getname().c_str(), dog.getage(), dog.getsound().c_str(), dog.getowner().c_str());
    }
    return 0;
}