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

How to create and access multiple objects based on user input - C++

本文关键字:对象 C++ 访问 何根 用户 输入 创建      更新时间:2023-10-16
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: Yesn0:     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("nn%s is a dog who is %d years old, says %s and %s the ownernn",
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());

您的代码存在一些问题。

首先:您在不同的作用域中声明了两个具有相同名称的变量:string namemain()作用域中,Dog namedo ... while作用域中。Dog对象仅存在于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: Yesn0:     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("nn%s is a dog who is %d years old, says %s and %s the ownernn",
dog.getname().c_str(), dog.getage(), dog.getsound().c_str(), dog.getowner().c_str());
}
return 0;
}