首页 > 解决方案 > 为什么在类与继承的情况下输出与所需的输出不同?

问题描述

在下面的代码中,如果语句没有被执行,并且所需的输出与输出不同。

using namespace std;
#include <iostream>

class Person{
public:
    int age;
    Person(int initialAge);
    void amIOld();
    void yearPasses();
};

Person::Person(int initialAge){
    // Add some more code to run some checks on initialAge


if (initialAge < 0)
{
    age = 0;
cout << "Age is not valid, setting age to 0." << endl;
}

 else (initialAge = age)
 ;


}

void Person::amIOld(){
    // Do some computations in here and print out the correct statement to the console 
    if (age < 13)
    cout << "You are young." << endl;

    else if (age >= 13 && age < 18)
    cout << "You are a teenager."<< endl;

    else(cout << "You are old."<< endl)
    ;

}

void Person::yearPasses(){
    // Increment the age of the person in here
age ++;
}

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;

}

输出不同于所需的输出。我不明白为什么在上面给出的代码中没有执行 else satetment。我对编码比较陌生。

样本输入

    4
   -1
    10
    16
    18

样本输出

    Age is not valid, setting age to 0.
    You are young.
    You are young.

    You are young.
    You are a teenager.

    You are a teenager.
    You are old.

    You are old.
    You are old

我的输出

    Age is not valid, setting age to 0.
    You are young.
    You are young.
    You are young.
    You are young.
    You are young.
    You are young.
    You are young.
    You are young.

非常感谢您的帮助。提前致谢。

标签: c++classif-statement

解决方案


分配是错误的方式

else (initialAge = age)

应该;

else
  age = initialAge;

更好的是,使用成员初始化列表,https://en.cppreference.com/w/cpp/language/constructor


推荐阅读