c++ - 类和构造函数
问题描述
using namespace std;
#include <iostream>
class Person {
public:
int age;
Person(int initialAge);
void amIOld();
void yearPasses();
};
Person::Person(int initialAge)
{
if (initialAge > 0) {
initialAge = age;
}
else if (initialAge < 0) {
cout << "Age is not valid, setting age to 0. \n";
age = 0;
}
// Add some more code to run some checks on initialAge
}
void Person::amIOld()
{
if (age < 13) {
cout << "You are young. \n";
}
else if (age >= 13 && age <= 18) {
cout << "You are a teenager. \n";
}
else if (age > 18) {
cout << "You are old. \n";
}
// Do some computations in here and print out the correct statement to the console
}
void Person::yearPasses()
{
age = age + 1;
// Increment the age of the person in here
}
int main()
{
int t;
int age;
cin >> t;
for (int i = 0; i < t; i++) {
cin >> age;
Person p(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
cout << '\n';
}
return 0;
}
输入 4 -1 10 16 18
预期输出:
年龄无效,将年龄设置为 0。您还年轻。你很年轻。
你很年轻。你是一个少年。
你是一个少年。你老了。
你老了。你老了。
我得到的输出是:
年龄无效,将年龄设置为 0。您还年轻。你很年轻。
你很年轻。你很年轻。
你很年轻。你很年轻。
你很年轻。你很年轻。
解决方案
问题出在构造函数中。使用初始化列表来避免此类问题。就像是
Person::Person(int initialAge):age(initialAge > 0 ? initialAge : 0)
{}
推荐阅读
- github - 进行上下文 github 检查以通过
- python - 从列表中删除所有可重复的值以及其他值中的值,Python
- jquery - 在 ASP.NET Core 控制器中传递多个 POST 参数
- java - 在接受多个输入时,使用扫描仪类在 Java 中遇到问题
- python - Django 按名称查询 content_type 而不是 content_type_id
- r - 如何取消列出字符串列以计算匹配项?
- json - 在 Dart/Flutter 中解析嵌套的 JSON
- python - 微调超参数不会提高分类器的分数
- angular - 角 9 SSR | 无法访问 ads.txt 文件
- postgresql - 如何在 PostgreSQL 中通过 cmd 使用 pg_restore 命令恢复 .bak 文件?