2011-11-24 18 views
0

我有類目錄當中做的東西與類文件的對象,重載運營商,像這樣的權利:程序不調用重載操作

class Directory 
{ 
    std::vector<char> name, timeOfCreation; 
    std::vector<File> arr; 

public: 
    Directory(std::string); 
    Directory(const Directory&); 
    ~Directory(); 


    Directory operator += (File); 
    Directory operator += (Directory); 
    Directory operator -= (File); 
    Directory operator ~(); 
    File operator [] (int); 
    operator int(); 

    friend bool operator % (Directory, File); 
    friend bool operator % (Directory, Directory); 
    friend Directory operator + (Directory, Directory); 
    friend Directory operator - (Directory, Directory); 
    friend long int operator + (Directory); 
    friend std::ofstream& operator << (std::ofstream&, Directory); 

friend void main(); 
}; 

好了,現在的問題出現時,在主,我有

void main() 
{ 
    //make object of Directory d 
    std::cout << d; 
} 

程序現在調用操作INT(),而不是運營商< <。因此,命令 std::cout <<d行爲像std::cout << (int)d,它在我的目錄中寫入了文件的數量。

下面是運營商< <和int()函數的實現:

Directory::operator int() 
{ 
    return (int)arr.size(); 
} 

std::ofstream& operator << (std::ofstream& out, Directory d) 
{ 
    // get the max field widths for three fields 
    int widthLeft = 0, widthMiddle = 0, widthRight = 10; 
    std::vector<File>::const_iterator i = d.arr.begin(); 
    for(; i < d.arr.end(); ++i) 
    { 
     if((int)d.timeOfCreation.size() > widthLeft) 
      widthLeft = (int)d.timeOfCreation.size(); 
    if((int)d.name.size() > widthMiddle) 
      widthMiddle = (int)d.name.size(); 
    } 
    out<<std::setw(widthLeft)<<"Date & Time of creation"; 
    out<<std::setw(widthMiddle)<<"Name"; 
    out<<std::setw(widthRight)<<"Total Size\n"; 
    return out; 

} 

注:操作員< <還沒有完成,我只是測試運輸及工務局局長的功能,但它仍然應該寫出一條線。

+0

你有沒有命名空間? 'operator <<'定義在哪裏?爲什麼你首先有一個轉換運算符爲'int'? –

回答

3

coutostream,不是ofstream

應該工作:

std::ostream& operator << (std::ostream&, Directory) 

你可能想通過目錄作爲參考。

+0

是的,它的工作,thanx :) – Vidak

1

你超載<<應與ostream工作,基類,而不僅僅是ofstream

friend std::ostream& operator << (std::ostream&, Directory const &); 

std::cout不是ofstream,所以它不會匹配您的過載。 (通過常量引用而不是值傳遞複雜對象也是一個好主意)。

而且,轉換運營商通常是一個壞主意,因爲一來他們會帶來惱人的隱式轉換像你在這裏找到,因爲他們可以迷惑類的用戶。它更有意義通過命名功能(size(),或file_count(),或其他)找到的文件目錄中的數量,比自己奇蹟般地改變成特定信息的目錄。

+0

它的工作,感謝您的洞察力。哦,順便說一下,有沒有辦法將三個值寫入一個ostream,但格式化爲一個向左沖刷,一個向右,而另一個設置爲從中間的某個位置開始。我在與運輸及工務局局長... – Vidak

+0

@Vidak麻煩:setw'的'組合'left'和'right'應該做你想要的東西 - 參見[這裏](http://cplusplus.com/reference/iostream /操縱器/)的細節。如果你無法弄清楚,請提出一個關於它的新問題。 –