4. Complete the program#
点击查看考点
类的基础语法
Implement Date
class and FinalTest
class, and make the main function ouput correctly. All data members should be private.
Tips:
Data validation is not required.
It is only required to implement the necessary member functions.
Interface and implementation are not necessarily separated.
翻译
实现 Date
和 FinalTest
从而让 main 函数正确输出. 所有数据成员都应该是私用的.
提示:
不需要进行数据有效性验证.
只需实现必需的成员函数.
接口和实现不必分离.
main.cpp#
1int main() {
2 FinalTest item1("C++ Test", Date(2014, 6, 2));
3 item1.print();
4 FinalTest item2("Java");
5 item2.print();
6 item2.setDue(Date(2014, 6, 10));
7 item2.print();
8}
Output#
1Title: C++ Test
2Test Date: 2014-6-2
3Title: Java
4Test Date: 2014-1-1
5Title: Java
6Test Date: 2014-6-10
点击查看解答参考
警告
此卷的所有解答参考都是笔者考试时实际写的代码的回忆版, 所以 相比于其他卷的解答参考可能更为超纲难懂.
主要是在展示以 "C++98 + Lambdas + range-based for + auto + STL" 为学习内容能如何秒杀转专业题目.
注意主程序中构造 Date
的表达式为 Date(2014, 6, 2)
, 而非 Date{2014, 6, 2}
. 这意味着对于考试的 C++ 标准 (C++20 以前) 要让这段代码通过编译, 必须定义一个构造函数, 而不能依赖于 struct
的列表初始化:
1struct Date {
2 public:
3 int year;
4 int month;
5 int day;
6};
7
8void f() {
9 Date a(2014, 6, 2); // 错误!
10 Date a{2014, 6, 2}; // 正确
11}