最近在看C++入门的书籍,但是光看是不够的,需要一些练习将知识运用起来,牛客网上面有在线编程的题目,我选择了一些入门的题目作为练习。
1、题目
这道题的题目如下:
2、解题
题目是非常简单的,但是因为只是看过了一遍知识点,没有动手实践,所以看起来很简单的东西,并没有想象中的掌握那么好。
2.1 构造函数
构造函数这个概念,我只记得它的名称和类的名称是相同的,看了一遍之前的笔记才想起来,构造函数的功能是在创建类对象的时候进行一些必要的操作。我用构造函数对三个int变量赋初值为0:
TDate::TDate() {
Month = 0;
Day = 0;
Year = 0;
}
还有另一种形式也可以实现赋初值,叫做初始化列表:
TDate::TDate(int a, int b , int c):Month(a), Day(b), Year(c) {
}
这样做的好处是,在对类对象初始化的时候,直接将值赋给私有变量,但是需要在声明类对象的时候进行操作:
TDate test(1,2,3);
2.2 格式化输出
我们在使用C语言的时候会使用sprintf函数,对字符串进行格式化输出,但是在C++中,使用string,是否有类似sprintf函数功能的操作呢?参考了博文:https://blog.csdn.net/gll028/article/details/17055283/中的方法:
std::ostringstream ostr;
ostr << Day << "/" << Month << "/" << Year;
std::string date = ostr.str();
std::cout << date << std::endl;
需要添加头文件:
#include <iostream>
#include <string>
最后的实现代码如下:
#include <iostream>
#include <string>
#include <sstream>
class TDate {
public:
TDate();
void print_date();
void get_date();
private:
int Month;
int Day;
int Year;
};
TDate::TDate() {
Month = 0;
Day = 0;
Year = 0;
}
void TDate::print_date() {
std::ostringstream ostr;
ostr << Day << "/" << Month << "/" << Year;
std::string date = ostr.str();
std::cout << date << std::endl;
}
void TDate::get_date() {
std::cin >> Year >> Month >> Day;
}
int main(void) {
TDate test;
test.get_date();
test.print_date();
}