2013-10-27 49 views
3

例如,命名空間標識符應該放在每個參數前面嗎?

Matrix.h

namespace Matrix 
{ 
    class mat 
    { 
    public: 
     mat(int row, int col); 
     const mat &operator=(const mat &rhs); 
    } 
} 

Matrix.cpp

Matrix::mat::mat(int row, int col) 
{ // implementation here } 

const Matrix::mat &Matrix::mat::operator=(const mat &rhs) 
{ // implementation here } 

上面的代碼將編譯沒有任何問題。問題是,我應該把名稱空間標識符放在參數前面,例如const mat operator=(const Matrix::mat &rhs);
const Matrix::mat Matrix::mat::operator=(const Matrix::mat &rhs)?什麼是常規方式來做到這一點,爲什麼它會編譯而不添加標識符?

+1

你可以這樣做,或者在這些方法周圍使用'命名空間Matrix {...}。我更喜歡後者。 – memo1288

回答

2

只要定義你的代碼命名空間

Matrix.cpp

namespace Matrix { 

    mat::mat(int row, int col) 
    { // implementation here } 

    mat& mat::operator=(const mat &rhs) 
    { // implementation here } 

} //namespace Matrix 
1

這純粹是一種風格偏好這完全是個人的。在過去十年中,我曾與很多喜歡這種風格的人合作過。不過,大多數人似乎更喜歡其他方式。

如果您正在使用此約定的項目工作,請保持一致並執行相同操作。否則,做你喜歡的。但請記住,使用您問題中描述的樣式可能無法幫助您找到具有相同樣式偏好的人。

人們通常會做的是將定義放在與declarion相同的命名空間中,就像@billz在他的例子中顯示的那樣。另一種方法是在提供類定義之前將using namespace Matrix;放在Matrix.cpp文件的頂部(而不是頭文件),儘管這樣做有點不那麼直接和簡單。

希望這會有所幫助。祝你好運! :)

+2

只是爲了緩解潛在的問題:'使用命名空間矩陣'應該只在'Matrix.cpp'的頂部完成。 **從不**在頭文件中放置'使用名稱空間'聲明。 –

+1

@ZacHowland:是的。有些情況下,儘管你可能想這樣做,但不是在全球範圍內。我的風格偏好 - 在我的代碼中完全沒有'使用namespace' :) – 2013-10-27 02:06:43

相關問題