Loading... ## 一:空参构造函数 ```cpp #include<iostream> using namespace std; class Time{ private: int hour; int minute; int sec; public: // 空参 构造函数 Time(){ hour = 0; minute = 0; sec = 0; } public: friend ostream & operator << (ostream & output, Time & t); }; ostream & operator << (ostream & output, Time & t){ output << "时: " << t.hour << " 分:" << t.minute << " 秒:" << t.sec << endl; } int main(){ Time t1 = Time(); cout << t1; return 0; } ``` ## 二:带参数的构造函数 ```cpp #include<iostream> using namespace std; class Time{ private: int hour; int minute; int sec; public: // 带参数构造函数 Time(int h, int m, int s){ hour = h; minute = m; sec = s; } public: friend ostream & operator << (ostream & output, Time & t); }; ostream & operator << (ostream & output, Time & t){ output << "时: " << t.hour << " 分:" << t.minute << " 秒:" << t.sec << endl; } int main(){ Time t1 = Time(1, 2, 3); cout << t1; return 0; } ``` ## 三:在构造函数中使用参数初始化表 ```cpp #include<iostream> using namespace std; class Time{ private: int hour; int minute; int sec; public: // 参数初始化表构造函数 Time(int h, int m, int s) : hour(h), minute(m), sec(s){ }; public: friend ostream & operator << (ostream & output, Time & t); }; ostream & operator << (ostream & output, Time & t){ output << "时: " << t.hour << " 分:" << t.minute << " 秒:" << t.sec << endl; } int main(){ Time t1 = Time(1, 2, 3); cout << t1; return 0; } ``` ## 四:使用默认参数构造函数 ```cpp #include<iostream> using namespace std; class Time{ private: int hour; int minute; int sec; public: // 默认参数构造函数 Time(int h = 0, int m = 0, int s = 0){ hour = h; minute = m; sec = s; } public: friend ostream & operator << (ostream & output, Time & t); }; ostream & operator << (ostream & output, Time & t){ output << "时: " << t.hour << " 分:" << t.minute << " 秒:" << t.sec << endl; } int main(){ Time t1 = Time(); cout << t1; return 0; } ``` ## 五:构造函数重载 ```cpp #include<iostream> using namespace std; class Time{ private: int hour; int minute; int sec; public: // 空参 构造函数 Time(){ hour = 0; minute = 0; sec = 0; } // 参数初始化表 构造函数 Time(int h, int m, int s) : hour(h), minute(m), sec(s) {}; public: friend ostream & operator << (ostream & output, Time & t); }; ostream & operator << (ostream & output, Time & t){ output << "时: " << t.hour << " 分:" << t.minute << " 秒:" << t.sec << endl; } int main(){ Time t1 = Time(1, 2, 3); Time t2 = Time(); cout << t1 << t2 << endl; return 0; } ``` 最后修改:2022 年 06 月 28 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果文章有用,请随意打赏。