我在通過函數傳遞常量類時遇到了問題。將const的CName傳遞爲此參數會丟棄限定符
// test the constructors
auto CName nameOne("Robert", "Bresson");
const CName nameTwo = nameOne;
auto CName nameThree;
// display the contents of each newly-constructed object...
// should see "Robert Bresson"
cout << "nameOne = ";
nameOne.WriteFullName();
cout << endl;
// should see "Robert Bresson" again
cout << "nameTwo = ";
nameTwo.WriteFullName();
cout << endl;
只要編譯器命中nameTwo.WriteFullName()我得到放棄限定符的錯誤。我知道這個班是一個常數,但我無法弄清楚如何解決這個問題。
功能是寫成這樣一個頭文件:
void const WriteFullName(ostream& outstream = cout)
{
outstream << m_first << ' ' << m_last;
}
我收到此錯誤時,常量被放在函數頭的背面
main.cpp:(.text+0x51): undefined reference to `CName::CName()'
main.cpp:(.text+0x7c): undefined reference to `CName::WriteFullName(std::basic_ostream<char, std::char_traits<char> >&) const'
main.cpp:(.text+0xbb): undefined reference to `CName::WriteFullName(std::basic_ostream<char, std::char_traits<char> >&) const'
main.cpp:(.text+0xf7): undefined reference to `CName::WriteFullName(std::basic_ostream<char, std::char_traits<char> >&) const'
main.cpp:(.text+0x133): undefined reference to `operator>>(std::basic_istream<char, std::char_traits<char> >&, CName&)'
main.cpp:(.text+0x157): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CName const&)'
main.cpp:(.text+0x1f4): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CName const&)'
main.cpp:(.text+0x22b): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CName const&)'
main.cpp:(.text+0x25f): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CName const&)'
main.cpp:(.text+0x320): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CName const&)'
main.cpp:(.text+0x347): undefined reference to `operator>>(std::basic_istream<char, std::char_traits<char> >&, CName&)'
一個小而不相關的提示:不要像你這樣使用'auto'。在舊的C++ 03標準中,它確實沒有做任何事情,而在新的C++ 11標準中,它被用來推斷變量的類型。 –
啊,謝謝,它是我老師灌輸給我們的一種老習慣。自動被用來在程序結束時自動創建和丟棄? –
爲了使函數爲const,你必須提供關鍵字AFTER函數名和簽名:void void WriteFullName(ostream&outstream = cout)const {/ *你的代碼* /}' – Rost