加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c使用time()同时包含两者 – 哪一个优先?

发布时间:2020-12-16 09:45:12 所属栏目:百科 来源:网络整理
导读:我正在使用GNU / Linux发行版与Zsh 5.0.2,Vim 7.3和GCC 4.8.0来学习C语言. 由于重新定义函数foo,以下代码将无法编译: #include iostreamint foo(){ return 0;}int foo(){ return 0;}int main(){ foo(); return 0;} 试图编译它: ? g++ -g -pedantic -std=c+
我正在使用GNU / Linux发行版与Zsh 5.0.2,Vim 7.3和GCC 4.8.0来学习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()
     ^

但是,我注意到GCC(g,具体而言)自动包含< time.h>没有我明确指示它这样做.在我编写的程序中,使用了std :: time(),但我忘了#include< ctime>并使用std ::前缀导致来自< time.h>的time()用来代替< ctime>中的相应函数.我很好奇 – 当两者都被包括时,哪个时间()会被使用?据我所知,两者都有一个名称的功能(并且它们都以类似或相同的方式工作),请参阅:

cppreference.com: time.h time()

cppreference.com: ctime 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>之一.和< ctime>可以调用变体.

问题1:为什么这个(function4)不会因模糊而导致错误或警告?

问题2:使用哪种变体以及哪种变体优先于另一种变体?

问题3:有没有办法在运行或编译过程中完整地输出函数名称以查看使用的库?

解决方法

请注意,不推荐使用C中的C头;并且无法保证C头将定义转储到全局命名空间以及std中.任何答案都将特定于您的实施.

Why doesn’t this (function4) result in an error or a warning due to ambiguity?

有两个原因:

>您可以根据需要随时声明功能.在此实现中,大多数C函数仅在头文件中具有预编译库中的定义的声明.
>标题包含防护,因此即使它们定义了函数,它们也可以安全地被包含多次.

Which variant is used and what determines that one takes precedence over the other?

在全局命名空间中,它将是在两个标头中声明的版本;两者都声明了相同的功能.一般来说,未指定C头是否也声明该函数以及std namepsace中的函数;在你的实现中,确实如此.

Is there a way to,say,output the function name in its entirety during a run or compilation process to see what library is used?

也许;但是没有意义,因为它将是相同的功能,无论哪个标头声明它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读