c++ - 为什么在类与继承的情况下输出与所需的输出不同?
问题描述
在下面的代码中,如果语句没有被执行,并且所需的输出与输出不同。
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.
非常感谢您的帮助。提前致谢。
解决方案
分配是错误的方式
else (initialAge = age)
应该;
else
age = initialAge;
更好的是,使用成员初始化列表,https://en.cppreference.com/w/cpp/language/constructor
推荐阅读
- ruby-on-rails - 使用 Turbolinks 时无法运行特定于页面的 javascript 包
- c# - Azure Function App 错误“无法解析远程名称”
- ruby-on-rails - 如何在 where 查询中使用参数 - Ruby?
- c - 等效表达式 memset 和数组
- angularjs - MVC 控制器方法未从 $http post 接收 json 数据
- ios - 如何在其他开发人员设备中安装我的 xcode 项目以进行测试
- android - 当我尝试使用 FloatingActionButton 打开 Main2Activity 时应用程序崩溃
- python - Python Bot 中的子命令
- c - 带有存储类说明符的空声明/声明说明符中有两种或多种数据类型
- c++ - Compaq Visual Fortran 对 DFOR.LIB 的引用