【C++】入门题目之定义Dog类
相信你是最棒哒!!!
文章目录
一、问题描述
二、题目代码
1.解析版
2.简洁版
总结
一、问题描述
定义一个Dog类,包含age, weight等数据成员,以及对这些数据成员操作的方法。实现并测试这个类。
前置代码:
#include<iostream>
using namespace std;
//请在此处定义dog类
后置代码:
int main()
{
Dog Jack(2,10);
cout<<"Jack is a Dog who is ";
cout<<Jack.getAge()<<" years old and "<<Jack.getWeight()<<" pounds weight"<<endl;
Jack.setAge(7);
Jack.setWeight(20);
cout<<"Now Jack is ";
cout<<Jack.getAge()<<" years old and "<<Jack.getWeight()<<" pounds weight."<<endl;
return 0;
}
输出样例:
Jack is a Dog who is 2 years old and 10 pounds weight
Now Jack is 7 years old and 20 pounds weight.
二、题目代码
1.解析版
// 包含标准库头文件(注意:<bits/stdc++.h>是非标准头文件,仅适用于竞赛/学习环境)
// 在实际项目中建议使用具体的头文件如<iostream>
#include<bits/stdc++.h>
using namespace std; // 使用标准命名空间(简化代码,但在大型项目中可能造成命名冲突)// Dog类定义
class Dog {// 私有成员变量(封装数据,外部不能直接访问)int age; // 狗的年龄int weight; // 狗的体重public:// 构造函数:初始化狗的年龄和体重// 参数:a - 年龄,w - 体重Dog(int a, int w) {age = a; // 初始化年龄weight = w; // 初始化体重// 注:更推荐使用成员初始化列表:Dog(int a, int w) : age(a), weight(w) {}}// 获取年龄// 返回值:狗的当前年龄// 注:应该添加const修饰,因为不修改对象状态:int getAge() const { return age; }int getAge() {return age;}// 获取体重// 返回值:狗的当前体重// 同样应该添加const修饰int getWeight() {return weight;}// 设置年龄// 参数:a - 要设置的新年龄void setAge(int a) {age = a; // 更新年龄}// 设置体重// 参数:w - 要设置的新体重void setWeight(int w) {weight = w; // 更新体重}
};// 主函数
int main() {// 创建一个名为Jack的Dog对象,初始年龄2岁,体重10磅Dog Jack(2, 10);// 输出Jack的初始信息cout << "Jack is a Dog who is ";// 通过getter方法获取并输出年龄和体重cout << Jack.getAge() << " years old and " << Jack.getWeight() << " pounds weight" << endl;// 修改Jack的年龄和体重Jack.setAge(7); // 将年龄设置为7岁Jack.setWeight(20); // 将体重设置为20磅// 输出更新后的信息cout << "Now Jack is ";cout << Jack.getAge() << " years old and " << Jack.getWeight() << " pounds weight." << endl;return 0; // 程序正常结束
}
2.简洁版
#include<bits/stdc++.h>
using namespace std;
class Dog {int age, weight;
public:Dog(int a,int w) {age=a;weight=w;}int getAge(){return age;}int getWeight() {return weight;}void setAge(int a) {age = a;}void setWeight(int w) {weight = w;}
};int main()
{Dog Jack(2, 10);cout << "Jack is a Dog who is ";cout << Jack.getAge() << " years old and " << Jack.getWeight() << " pounds weight" << endl;Jack.setAge(7);Jack.setWeight(20);cout << "Now Jack is ";cout << Jack.getAge() << " years old and " << Jack.getWeight() << " pounds weight." << endl;return 0;
}
总结
类功能
-
数据存储:记录狗的
age
(年龄)和weight
(体重)。 -
方法提供:
-
构造函数
Dog(int a, int w)
:初始化狗的年龄和体重。 -
Getter方法
getAge()
和getWeight()
:获取狗的年龄和体重。 -
Setter方法
setAge(int a)
和setWeight(int w)
:修改狗的年龄和体重。
-
主程序逻辑
-
创建一个名为
Jack
的Dog
对象,初始年龄为 2 岁,体重为 10 磅。 -
打印
Jack
的初始信息。 -
通过
setAge
和setWeight
修改Jack
的年龄和体重。 -
打印修改后的信息