首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 模板類 show() 返回 void 無法用 cout 輸出:正確調用方式

     編輯:程式設計綜合問答

錯誤代碼

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;

修正方案二:show() 返回 ostream& 支持鏈式調用

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;       // 重定向到文件

修正方案三:重載 operator<< (最符合 C++ 慣用語)

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++ 標準庫風格。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved