如何根据用户输入创建和访问多个对象 - C++
How to create and access multiple objects based on user input - C++
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;
}
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象