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 name
在main()
作用域中,Dog name
在do ... 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;
}