首页 > 解决方案 > 类和构造函数

问题描述

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。您还年轻。你很年轻。

你很年轻。你很年轻。

你很年轻。你很年轻。

你很年轻。你很年轻。

标签: c++classconstructor

解决方案


问题出在构造函数中。使用初始化列表来避免此类问题。就像是

Person::Person(int initialAge):age(initialAge > 0 ? initialAge : 0)
{}

推荐阅读