话不多说,先上代码
#include<iostream>
#include<cstring>
#include<string>
#include<iomanip>
#include<fstream>
using namespace std;
class Date
{
private:
int year,month,day;
public:
Date():year(1),month(1){day=3;};
Date(int t1,int t2=5,int t3=5);
void print();
};
Date::Date(int s1,int s2,int s3){
year=s1;
month=s2;
day=s3;
}
void Date::print()
{
cout<<year<<" "<<month<<" "<<day<<endl;
}
int main()
{
Date w1;
Date w2(1);
Date w3(1,2);
Date w4(1,2,3);
w1.print();
w2.print();
w3.print();
w4.print();
return 0;
}
输出结果:
1 1 3
1 5 5
1 2 5
1 2 3
我感觉我已经不适合打代码了,把输出函数打成了 cout<<year<<" "<<month<<" "<<year<<endl;
我还搁那傻了吧唧的调。。。
在函数重载的时候有个地方需要注意,如果要初始化三个参数,则必须将Date();这个函数去掉,因为对于全部指定了默认值的构造函数,不能再定义其他参数类型与之相同的重载构造函数。
#include<iostream>
#include<cstring>
#include<string>
#include<iomanip>
#include<fstream>
using namespace std;
class Date
{
private:
int year,month,day;
public:
//Date():year(1),month(1){day=3;};
Date(int t1=1,int t2=5,int t3=5);
void print();
};
Date::Date(int s1,int s2,int s3){
year=s1;
month=s2;
day=s3;
}
void Date::print()
{
cout<<year<<" "<<month<<" "<<day<<endl;
}
int main()
{
Date w1;
Date w2(1);
Date w3(1,2);
Date w4(1,2,3);
w1.print();
w2.print();
w3.print();
w4.print();
return 0;
}
输出结果:
1 5 5
1 5 5
1 2 5
1 2 3