2011-09-27 89 views
4

我想要一個函數,輸出某些信息到輸入到該函數的特定指定源。在代碼中,我的意思是:在C++中創建一個函數輸出到指定的源

function output(source) { 

source << "hello" << endl; 

} 

其中源可以是ofstreamcout。所以,我可以打電話像這樣這個函數:

output(cout)ofstream otp ("hello"); output(otp)

我的問題是,我該如何定性source,使這項工作?這是公平地假設source將永遠是std類的成員

謝謝!

+2

其中兩個方面:1)'source' is on od d名稱爲數據*進入*的位置。不使用*來源*來源?2)當你的意思是'\ n''時,千萬不要說'endl'。見['endl'慘敗](http://stackoverflow.com/questions/5492380/what-is-the-c-iostream-endl-fiasco/5492605#5492605)。 –

+0

@Rob:你說得對,'source'可能應該改變。並非常感謝你對'endl'的慘敗。我不知道在**所有**!特別是當我的程序要做很多I/O時!完美評論,+1 – Amit

回答

7
void output(std::ostream &source) { 
    source << "hello" << std::endl; 
} 

甚至:

template <T> 
void output(T &source) { 
    source << "hello" << std::endl; 
} 
+0

非常感謝,這工作。 – Amit

4

寫您的功能:

std::ostream& output(std::ostream& source) 
{ 
    return source << "hello" << endl; 
} 

然後你可以使用它作爲:

output(cout); 

//and 
ofstream otp ("hello"); 
output(otp); 

//and 
output(output(cout)); 
output(output(output(cout))); 
output(output(output(output(cout)))); 

//and even this: 
output(output(output(output(cout)))) << "weird syntax" << "yes it is" ; 

順便說一句,如果output函數有很多行,那麼你可以爲它寫:

std::ostream& output(std::ostream& source) 
{ 
    source << "hello" << endl; 
    source << "world" << endl; 
    //.... 
    return source; 
} 

的一點是,它應該返回source。在早期版本中,函數返回source

+1

哦,上帝是瘋了!但是謝謝你:) – Amit

1

你應該傳遞一個std::ostream&作爲參數

0

恕我直言,重定向輸出應該在用戶級別來完成。寫你的C++這樣的:

cout << "hello" << endl; 

和執行應用程序時,用戶可以將輸出重定向到任何他想做的,說一個文件:

myapp > myfile 
+0

你當然是對的,我打算這麼做。但是我的應用程序輸出很多信息,這些信息對於我需要這個特定文件的計算來說有點不相關。所以我喜歡選擇消息來源。 – Amit

+0

您可以隨時過濾文件,或者只是重定向您想要的內容,或者爲每個文件使用不同的輸出流。以防萬一你不知道,你仍然可以重定向任何輸出流,如myapp 2> myfile,myapp 3> myfile等等。 – m0skit0

1
function output(source) { 
    source << "hello" << endl; 
} 

如果這是一個成員函數,其中的一點是轉儲有關它所屬類別的對象的數據,考慮將其重命名爲operator<<。所以,與其

class Room { 
    ... 
    // usage myRoom.output(otp) 
    void output(std::ostream& stream) { 
    stream << "[" << m_name << ", " << m_age << "]"; 
    } 
}; 

相反,試試這個:

class Room { 
    ... 
    // usage opt << myRoom << "\n" 
    friend std::ostream& operator<<(std::ostream& stream, const Room& room) { 
    return stream << "[" << room.m_name << ", " << room.m_age << "]"; 
    } 
}; 

這樣的話,你可以使用更自然的語法顯示您的類的狀態:

std::cout << "My Room: " << myRoom << "\n"; 

代替klunky

std::cout << "My Room: "; 
myRoom.output(std::cout); 
std::cout << "\n"; 
相關問題