我使用带有 Zsh 5.0.2、Vim 7.3 和 GCC 4.8.0 的 GNU/Linux 发行版来学习 C++。
由于函数的重新定义,以下代码将无法编译foo
:
#include <iostream>
int foo()
{
return 0;
}
int foo()
{
return 0;
}
int main()
{
foo();
return 0;
}
尝试编译它:
» g++ -g -pedantic -std=c++11 -Wall -Wextra -Weffc++ foo.cpp -o foo
fail.cpp: In function ‘int foo()’:
fail.cpp:8:5: error: redefinition of ‘int foo()’
int foo()
^
fail.cpp:3:5: error: ‘int foo()’ previously defined here
int foo()
^
然而,我注意到海湾合作委员会(g++
,具体来说)自动包括<time.h>
没有我明确指示它这样做。在我写的一个程序中std::time()
已使用但我忘记了#include <ctime>
并使用std::
前缀这导致time()
from <time.h>
用于代替相应的函数<ctime>
。我很好奇 - 当 和 都包含时将使用哪个 time() ?据我所知,两者都有一个同名的函数(并且它们都以相似或相同的方式工作),请参阅:
cppreference.com:time.h time() http://en.cppreference.com/w/c/chrono/time
cppreference.com:ctime 时间() http://en.cppreference.com/w/cpp/chrono/c/time
考虑以下代码:
#include <ctime>
#include <time.h>
#include <iostream>
int function1()
{
using namespace std;
cout << "function4: " << time(NULL) << endl;
return 0;
}
int function2()
{
using std::time;
std::cout << "function3: " << time(NULL) << std::endl;
return 0;
}
int function3()
{
std::cout << "function2: " << std::time(NULL) << std::endl;
return 0;
}
int function4()
{
std::cout << "function1: " << time(NULL) << std::endl;
return 0;
}
int main()
{
function1();
function2();
function3();
function4();
return 0;
}
它可能并不完美,但我希望我的观点能够得到理解。在这里,我明确地包括了<time.h>
为清楚起见。前三个以我所知道的方式声明std
是要使用的。第四个函数简单地调用time()
- 对我来说这似乎是其中之一<time.h>
and <ctime>
可以调用变体。
问题一:为什么此 (function4) 不会因不明确而导致错误或警告?
问题2:使用哪种变体以及什么决定一个变体优先于另一个变体?
问题3:有没有一种方法可以在运行或编译过程中输出完整的函数名称以查看使用的库?