我有 Human 类和 MealPlanner 类。
我在 Mealplanner 类中创建了 Human 对象,但我需要将参数输入到 Human 中。例如,它有年龄、体重和高度。
所以首先它就像
MealPlanner::MealPlanner(){
humanP = new Human;
/// But human actually has parameters like Human(weight, age, ...)
/// I just need those parameters to be entered by the user
}
我应该只在 MealPlanner 中创建一个函数吗
MealPlanner::enterInfo(){
int age;
cout << "enter age" << endl;
cin >> age;
/// and so on
///and then do
humanP->setAge(age);
}
通常我会在 main() 中输入所有信息,然后将对象传递给 MealPlanner,但我的任务是基本上在 MealPlanner 类中创建对象,最好的方法是在其中创建 Human 对象。但是人类需要信息,我应该让用户在哪里输入这些信息?
还有为什么在类内部使用 cout 是不好的做法?
最佳答案
假设humanP
是指向类型 Human
的指针这是 MealPlanner
的成员变量(即字段) .由于它是一个指针,因此您需要调用 operator new()
初始化它 - 但在这种特殊情况下(如您在所有者的构造函数中创建的那样),制作 humanP
可能更好一个常规变量。
这样它将默认隐式构造 - 您不需要显式构造它。
关于读取输入/输出:理想情况下,您应该拆分用户输入/验证和数据修改。因此,想象一个图层类或函数执行输入/输出过程,然后调用 MealPlanner::setHumanData(age, weight, height)
.
关于c++ - 我需要为类输入参数,应该在哪里输入?还有为什么 cout 被认为是在类里面使用的不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41086978/