template
void List::show() {
for (int i = 0; i < length; i++)
cout << element[i] << endl;
}
void main() {
List MyList(5);
// ...
cout << "MyList is: " << MyList.show() << endl; // 編譯錯誤
}
show() 返回類型是 void,**無返回值**,不能作為 operator<< 的右操作數。編譯器報錯:no match for 'operator<<' (operand types are 'std::ostream' and 'void')。
cout << "MyList is: ";
MyList.show();
cout << endl;
template
ostream& List::show(ostream& os = cout) { // 默認參數 cout
for (int i = 0; i < length; i++)
os << element[i] << ' ';
return os;
}
// 調用
MyList.show() << endl; // 使用默認 cout
MyList.show(cout) << endl; // 顯式傳遞
ofstream file("data.txt");
MyList.show(file) << endl; // 重定向到文件
template
class List {
// ...
friend ostream& operator<<(ostream& os, const List& list) {
for (int i = 0; i < list.length; i++)
os << list.element[i] << ' ';
return os;
}
};
// 調用
cout << "MyList is: " << MyList << endl;
| 場景 | 推薦方式 |
|---|---|
| 僅調試輸出 | 方案一:分離語句 |
| 需靈活輸出目標 (文件/字符串/網絡) | 方案二:傳遞 ostream& |
| 類作為標準容器風格使用 | 方案三:重載 operator<< |
模板類的**成員函數定義必須在頭文件中** (或包含 .tpp/.inl),否則鏈接階段報 undefined reference。正確結構:
// List.h
template
class List {
public:
List(int maxSize = 10);
void show(); // 或 ostream& show(ostream&)
private:
T *element;
int length, maxSize;
};
#include "List.inl" // 或直接在這裡寫實現
// List.inl
template
List::List(int maxSize) : maxSize(maxSize), length(0) {
element = new T[maxSize];
}
template
void List::show() { /* ... */ }
void 函數不能參與流輸出表達式。選擇**分離語句**、**返回 ostream&**、**重載 operator<<** 三種方式之一,推薦方案三符合 C++ 標準庫風格。