iostream 头文件是否只包含声明?



我正在学习C++编程。我正在编写一个程序来实现计算器功能:

可以看出,我正在包含iostream头文件。

#include <iostream>
#include "calculator.h"
int main()
{
//This program is meant to mimic the functionality of a calculator which 
//support basic arithmetic operations.
//we will ask the user to input the desired operation and operands 
getUserInput();
//We perform the mathematical operation and return the result
computeResult();
//We will print the output to the screen
printResult();
return 0;
}

现在我正在为 getUserInput 函数编写一个单独的 cpp 文件。

#include<iostream>
int getUserInput()
{
int a;
std::cout << "enter your input " << std::endl;
std::cin >> a;
return (a);
}

在这里,我也包括iostream。可以这样做吗?

因为,我怀疑如果iostream包含定义,这可能会导致 与多个定义相关的链接错误。

您说得对,包含全局名称定义的标头不能包含在多个源文件中,否则会导致链接错误。标准标头不会这样做。

iostream 头文件是否只包含声明?

不。它还包含定义。例如,指定包括定义类模板(如std::basic_istream等)的<ios>

在这里,我也包括iostream。可以这样做吗? 因为,我怀疑如果iostream包含定义,这可能会导致与多个定义相关的链接错误。

<iostream>以及所有其他标准标头都将受到标头保护或类似机制的保护,以确保尽管有多个包含宏,但内容仅包含一次。此外,它们不会包含任何根据一个定义规则不允许位于多个翻译单元中的定义。

所以,是的:可以多次包含标准标头。既可以在一个翻译单元内,也可以从多个单独的翻译单元中获取。

最新更新