使えない変数名
プログラムに使う変数や関数にはわかりやすい名前をつけるべき、という理由からC++でcountという名前の変数をグローバルで宣言してコンパイルした。コンパイルエラー。STLアルゴリズムにある関数と名前がかぶった。
コンパイルエラー:
#include<iostream> using namespace std; int count; int main() { count=0; return 0; }
test.cpp: In function ‘int main()’: test.cpp:7: error: reference to ‘count’ is ambiguous test.cpp:4: error: candidates are: int count /usr/include/c++/4.2/bits/stl_algo.h:424: error: template<class _InputIterator, class _Tp> typename std::iterator_traits::difference_type std::count(_InputIterator, _InputIterator, const _Tp&) test.cpp:7: error: reference to ‘count’ is ambiguous test.cpp:4: error: candidates are: int count /usr/include/c++/4.2/bits/stl_algo.h:424: error: template<class _InputIterator, class _Tp> typename std::iterator_traits::difference_type std::count(_InputIterator, _InputIterator, const _Tp&)
エラーをなくすには:
std名前空間をusingしない
不便
#include<iostream> int count; int main() { std::count(~); count =0; }
ローカルで宣言
main関数内でcount関数が使えない
#include<iosteam> using namespace std; int main() { int count; }
グローバルでcountという変数名は使わないほうがよい?