C++ cout 自定義類別

本篇 ShengYu 介紹如何在 C++ 中 cout 自定義類別,

某天我寫了一個自定義的類別叫 Date,裡面存放著年月日,每當我要 cout 輸出時可能會這樣寫,

cpp-cout-myclass.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// g++ cpp-cout-myclass.cpp -o a.out -std=c++11
#include <iostream>
#include <fstream>
using namespace std;

class Date {
public:
Date(int y, int m, int d) : mMonth(m), mDay(d), mYear(y) {
}

int month() { return mMonth; }
int day() { return mDay; }
int year() { return mYear; }

private:
int mMonth = 0;
int mDay = 0;
int mYear = 0;
};

int main() {
Date date(2020, 12, 25);
cout << date.year() << '/' << date.month() << '/' << date.day() << "\n";
Date date2(2020, 3, 9);
cout << date2.year() << '/' << date2.month() << '/' << date2.day() << "\n";

return 0;
}

輸出如下,

1
2
2020/12/25
2020/3/9

每次要印出日期都要寫一樣這麼長的程式碼,我能不能讓 cout 印出我自定義類別想要印出的格式?
網路上找了一下資料,方法如下,

cpp-cout-myclass2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// g++ cpp-cout-myclass2.cpp -o a.out -std=c++11
#include <iostream>
#include <fstream>
using namespace std;

class Date {
public:
Date(int y, int m, int d) : mMonth(m), mDay(d), mYear(y) {
}

int month() { return mMonth; }
int day() { return mDay; }
int year() { return mYear; }
friend ostream& operator<<(ostream& os, const Date& d);

private:
int mMonth = 0;
int mDay = 0;
int mYear = 0;
};

ostream& operator<<(ostream& os, const Date& d) {
os << d.mYear << '/' << d.mMonth << '/' << d.mDay;
return os;
}

int main() {
Date date(2020, 12, 25);
cout << date << "\n";
Date date2(2020, 3, 9);
cout << date2 << endl;

return 0;
}

這樣輸出就跟之前一樣,但是程式碼就少很多,清爽許多了~~~

其它參考
c++ - How can I use cout << myclass - Stack Overflow
https://stackoverflow.com/questions/2981836/how-can-i-use-cout-myclass
為您的自訂類別多載 << 運算子 | Microsoft Docs
https://docs.microsoft.com/zh-tw/cpp/standard-library/overloading-the-output-operator-for-your-own-classes?view=msvc-160

其它相關文章推薦
C/C++ 新手入門教學懶人包
C/C++ 字串轉數字的4種方法
C++ virtual 的兩種用法
C/C++ 字串反轉 reverse
C/C++ call by value傳值, call by pointer傳址, call by reference傳參考 的差別
C++ 類別樣板 class template
std::sort 用法與範例
std::find 用法與範例
std::queue 用法與範例
std::map 用法與範例
std::deque 用法與範例
std::vector 用法與範例