默认参数写在类成员函数的声明里(.h头文件里),默认参数都必须在最右边
Time.hpp
//
// Time.hpp
// stud
//
// Created by pt on 2024/4/8.
//
#ifndef Time_hpp
#define Time_hpp
//类声明
#include <iostream>
using namespace std;
class Time
{
private:
int Millisecond;
void initMillTime(int mls);//成员函数的声明 -- 配套成员函数的实现
public:
int Hour;
int Minute;
int Second;
Time(int tmphour, int tmpmin, int tmpsec =3);//构造函数
Time();//构造函数
void initTime(int tmphour, int tmpmin, int tmpsec);//成员函数的声明 -- 配套成员函数的实现
void show(){std::cout << "hahaha" << std::endl;}//成员函数的定义
};
#endif /* Time_hpp */
Time.cpp
//
// Time.cpp
// stud
//
// Created by pt on 2024/4/8.
//
#include "Time.hpp"
Time::Time(int tmphour, int tmpmin, int tmpsec)//构造函数的实现
{
Hour = tmphour;
Minute = tmpmin;
Second = tmpsec;
initMillTime(0);//⬇️
}
Time::Time()//构造函数的实现
{
Hour = 12;
Minute = 59;
Second = 59;
initMillTime(59);
}
void Time::initMillTime(int mls)//成员函数的实现-- 配套成员函数的声明
{
Millisecond = mls;//私有成员
}
可以在真正初始化时用别的值,就会覆盖这个默认参数
main.cpp
#include <iostream>
#include "Time.hpp"
using namespace std;
int main()
{
Time moren(12,13,4);
std::cout << moren.Second << endl; //4
}