【发布时间】:2021-08-14 15:29:31
【问题描述】:
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。 你很年轻。 你还年轻。
你还年轻。 你还年轻。
你还年轻。 你还年轻。
你还年轻。 你还年轻。
【问题讨论】:
-
initialAge=age;- 这行有什么问题? -
当
initialAge == 0你不初始化成员时 -
为什么我得到的输出是“你还年轻”。不管我提供什么年龄?
-
@SakshiMishra 你明白
initialAge=age;和age=initialAge;之间的区别吗?
标签: c++ class constructor