2011-03-11 41 views
2

我有一個Visual Studio 2008的C++應用程序,我需要從接受一個可變大小的緩衝區功能獲取信息。所以,我有備份該類型與std::vector並實現了轉換操作符到我想要的類型的類。使用類型轉換操作符

class CMibIpForwardTable 
{ 
public: 
    operator MIB_IPFORWARDTABLE*() 
    { 
     return reinterpret_cast< MIB_IPFORWARDTABLE* >(&buffer_.front()); 
    } 

    ULONG size() const 
    { 
     return buffer_.size(); 
    } 

    void resize(ULONG size) 
    { 
     buffer_.resize(size); 
    } 

private: 
    std::vector<BYTE> buffer_; 
}; 

CMibIpForwardTable Get(DWORD* error_code = NULL) 
{ 
    CMibIpForwardTable table; 
    ULONG size = 0; 

    DWORD ec = ::GetIpForwardTable(NULL, &size, FALSE); 
    if(ec == ERROR_INSUFFICIENT_BUFFER) 
    { 
     table.resize(size); 
     ec = ::GetIpForwardTable(table, &size, TRUE); 
    } 

    if(NULL != error_code && ec != 0) 
     *error_code = ec; 
    return table; 
} 

我想能夠使用這樣的:

CMibIpForwardTable table = Get(); 

// error: 'dwNumEntries' : is not a member of 'CMibIpForwardTable' 
DWORD entries = table->dwNumEntries; 

是否有一個很好的方式來獲得訪問底層類型MIB_IPFORWARDTABLE?還是我堅持做這樣的事情:

MIB_IPFORWARDTABLE* t = table; 
DWORD entries = t->dwNumEntries; 

感謝, PaulH

回答

3

只是除了轉換操作符重載operator->

MIB_IPFORWARDTABLE* operator->() { ... } 
const MIB_IPFORWARDTABLE* operator->() const { ... } 
0

您可以重載operator->但是請您在進行此操作之前仔細考慮。一般情況下,在不具有完全透明的方式運算符重載會造成日後的維護問題。你有沒有考慮只增加一個「get_entries」功能,您的課嗎?

相關問題