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());
最佳答案
您的代码有一些问题。
首先:您在不同的作用域中声明了两个具有相同名称的变量:main()
作用域中的 string name
和 Dog name
do ... while
作用域。 Dog
对象仅存在于 do ... while
循环中。当您尝试在循环外访问它时,您会收到错误 ... has no member getname
因为您实际上访问的是 string
对象,而不是 狗
对象。
第二:您没有存储用户输入的狗
信息。
您需要使用 vector 来存储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;
}
关于c++ - 如何根据用户输入创建和访问多个对象 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546846/